[Tutor] variable from input?

Kent Johnson kent_johnson at skillsoft.com
Tue Oct 26 02:38:38 CEST 2004

I'm hesitant to answer this question because I'm not sure if you understand 
what you are asking for or if you are confused about variables and 
assignment. If you just want to remember the name the user entered, it is 
in the name variable and you can access it from there. That is the more 
common usage:
 >>> name = raw_input('What is your name? ')
What is your name? Kent
 >>> print name

But if you really want to you can access the global namespace directly with 
the globals() function. At first there is not much there:
 >>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 
'__doc__': None}

Assignment adds a new entry to the namespace:
 >>> x = 3
 >>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 
'__doc__': None, 'x': 3}

It works the other way around as well - adding a key to globals() creates a 
named variable:
 >>> globals()['Rene'] = 'Rene'
 >>> Rene
 >>> name = raw_input('What is your name? ')
What is your name? Kent
 >>> globals()[name] = name
 >>> Kent


At 07:53 PM 10/25/2004 -0400, Rene Lopez wrote:
>is it possible to have the user input something with a raw_input
>command, and then base upon the input make that into the name of a
>for example:
>answer = raw_input("what is your name?")
>user types in Rene, and some how we end up with a variable named Rene?
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list