Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python dumb newbie question about def

  1. Feb 4, 2012 #1
    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,

    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?
  2. jcsd
  3. Feb 4, 2012 #2


    User Avatar
    Gold Member

    Please use [code ] tags...
    Code (Text):

    [color=#008000][b]def[/b][/color] [color=#0000FF]examplr[/color]([color=#008000]str[/color]):
        [color=#008000][b]print[/b][/color] [color=#008000]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 (Text):

    [color=#008000][b]import[/b][/color] [color=#0000FF][b]example[/b][/color]
    to bring the module into the current namespace. Then, you can access you function as
    Code (Text):

  4. Feb 4, 2012 #3
    Thanks, that worked I hadnt imported it properly.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook