1

I am a newbie in python. I am trying to code a very basic function but getting errors. I dont know the reason behind it. Example code:

def printme( str ):
    print str;
    return;

printme("My string");

This should execute logically but it gives me the following error:

Traceback (most recent call last): File "stdin", line 1, in "module"
NameError: name 'printme' is not defined

Any suggestions are welcome...

6
  • 2
    You don't need the semicolons in Python. Commented Dec 2, 2010 at 1:27
  • Is that the exact copy and paste of your code? It gives me a indentation error on return; Commented Dec 2, 2010 at 1:27
  • 1
    is that a straight copy/paste? the return line isn't aligned with the print Commented Dec 2, 2010 at 1:28
  • 4
    Don't name a variable str, it's the name of a built-in type and overriding it is a Bad Idea. Commented Dec 2, 2010 at 1:32
  • No its not exact copy and paste Commented Dec 2, 2010 at 1:33

4 Answers 4

5

The semicolons shouldn't be there as well as the return statement (the execution of the function ends at the last statement indented within it).

Not entirely sure how you formated the indent but python relies on that to determine scope

def printme(str):
    print str #This line is indented, 
              #that shows python it is an instruction in printme

printme("My string") #This line is not indented. 
                     #printme's definition ends before this

executes currectly

wikipedia's page on python syntax covers the indentation rules.

Sign up to request clarification or add additional context in comments.

2 Comments

@ricky: Since Python doesn't use braces for scope, you need to have a consistent way of indenting blocks. Use either tab, or the same number of spaces every time, or Python will get confused about what block a statement belongs to.
I clarified what I meant regarding the semicolons and the indentation. Let me know if part of it still isn't clear.
2

It might help to follow the python style guide (pep8). You don't have to, but it will help avoid your indentation errors, and it will be easy to read other peoples code.

Comments

2

It does not work because of your indentation error. Your function never compiled so it does not exists.

(Original question has been edited away for 'proper formatting')

Comments

1

try cp this:

def printme(str):
    print str

printme("My string")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.