[Tutor] variable from input?

Jeff Shannon jeff at ccvcorp.com
Tue Oct 26 02:46:32 CEST 2004


Liam Clarke wrote:

>On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez <renx99 at gmail.com> 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
>>variable?
>>
>>for example:
>>
>>answer = raw_input("what is your name?")
>>
>>user types in Rene, and some how we end up with a variable named Rene?
>>
>That's an interesting one... 
>
>You could have the variable contained in a separate module, [...]
>
>But I've wondered that myself, but the implementation doesn't seem to
>be worth the effort.
>Once again, I could be entirely wrong.
>  
>

IMHO, you're not wrong.  It seems to me that, when one is looking at 
creating variables with names based on user input, then one should 
probably be looking at using either a dictionary or a class (or possibly 
both) instead.

    user_input = {}
    answer = raw_input("What is your name?")
    user_input[answer] = SomeUserSpecificInfo()

Variable names only have significance to someone who's actually looking 
at the code (whether reading it or writing it).  This means that it 
makes no sense to have a variable name depend on something that happens 
only at runtime -- you want the variable name(s) to be consistent every 
time the program runs. 

On the other hand, if you want your code to have a way to refer to a 
chunk of information based on something that a user types in, then 
dictionaries are exactly what you want.  All of the information is held 
in a reliable variable name that the programmer can easily find, and 
it's stored in a way that maps the information (dictionary value) to the 
"name" given by the user (dictionary key) in a simple and 
straightforward manner.  It prevents the potential problem of a user 
entering a variable name that's already used by the program.  (Consider 
what might happen, for instance, if the user entered their name as 
"print", which is a reserved keyword and thus a syntax error to use as a 
variable name... or if the user entered a name that just happened to be 
the same as one of the functions in your program...)  It also makes it 
very easy to store multiple copies of the information -- for example, 
one variable for each of several different users -- and to act on each 
set of data in a consistent and rational manner.  (In the O.P.'s 
example, it would be relatively difficult to run a function for each of 
Rene and Thomas and Eric and John; with a dictionary, it's trivial to 
put the function call into a for loop.)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Tutor mailing list