Why Does My Python Function Give a NameError in the Shell?

  • Context: Python 
  • Thread starter Thread starter funcosed
  • Start date Start date
  • Tags Tags
    Python
Click For Summary
SUMMARY

The discussion centers on a common issue faced by beginners in Python programming, specifically a NameError when attempting to call a function from a script. The user defined a function named examplr in a file called example.py but encountered a NameError when trying to invoke it in the Python shell. The solution provided emphasizes the necessity of importing the module using import example before calling the function, ensuring it is recognized in the current namespace.

PREREQUISITES
  • Basic understanding of Python syntax and function definitions
  • Familiarity with Python file execution and module importing
  • Knowledge of using the Python shell or IDLE for running scripts
  • Experience with error messages and debugging in Python
NEXT STEPS
  • Learn about Python module importing and namespace management
  • Explore Python function definitions and scope
  • Investigate common Python error messages and their resolutions
  • Practice writing and executing Python scripts in various environments
USEFUL FOR

Beginner Python programmers, educators teaching Python fundamentals, and anyone troubleshooting function-related errors in Python scripts.

funcosed
Messages
35
Reaction score
0
Newbie question...
I'm just learning python and need some help with creating functions. I want to create a function that is callable from python shell. I write a script as follows,

#!/usr/bin/python
def examplr(str):
print str

save it as example.py, then in shell try example('ddd') but it returns an error,
NameError: name 'example' is not defined. Anyone know what I am doing wrong?
 
Technology news on Phys.org
Please use [code ] tags...
Code:
[i]#!/usr/bin/python[/i][/color]
[b]def[/b][/color] examplr[/color](str[/color]):
    [b]print[/b][/color] str[/color]
Based on your code, you've named your function examplr.

If that's just a typo in your post, and you're correctly calling the function, then it sounds like you haven't imported your module into Python. If you're using IDLE, hit F5 to run the script. Otherwise, run the interpreter in the directory you've saved example.py and run
Code:
[b]import[/b][/color] [b]example[/b][/color]
to bring the module into the current namespace. Then, you can access you function as
Code:
example.[/color]example('foo'[/color])
 
Thanks, that worked I hadnt imported it properly.
 

Similar threads

  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 10 ·
Replies
10
Views
1K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K