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,

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

    jhae2.718

    User Avatar
    Gold Member

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

    [color=#408080][i]#!/usr/bin/python[/i][/color]
    [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):

    example[color=#666666].[/color]example([color=#BA2121]'foo'[/color])
     
     
  4. Feb 4, 2012 #3
    Thanks, that worked I hadnt imported it properly.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Python dumb newbie question about def
Loading...