Printing user input?

kyosohma at gmail.com kyosohma at gmail.com
Thu Nov 15 12:18:31 EST 2007


On Nov 15, 11:03 am, Mohammed_M <Moh... at gmail.com> wrote:
> Hi,
> I'm v.new to Python, so please don't be too harsh :)
> I get a NameError with the code below - All I want to do is store some
> input taken from the user in a variable called name, & then print name
>
> # START CODE ==========================================
> # Print name demo
>
> def PersonsDetails():
>     name = input("What's your name?")
> PersonsDetails()
>
> print(name)
>
> # END CODE ==========================================
>
> Thanks for reading & any help on this

It's a scope issue. You have the variable, "name", inside a function
and then you try to reference it outside the function, where it is not
defined. Thus, Python gives an error. To fix this, put the print
statement in the function itself...and when you use print, you don't
usually put the object to be printed in parentheses.

def PersonsDetails():
    name = input("What's your name?")
    print name
PersonsDetails()

See also this article on scopes and namespaces:

http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html
or
http://www.diveintopython.org/html_processing/locals_and_globals.html

Hope that helps some.

Mike



More information about the Python-list mailing list