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
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
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?
 
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.