Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get user input to refer to a variable in Python?

I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'?

list1 = ['cat', 'dog', 'juice']
list2 = ['skunk', 'bats', 'pogo stick']

x = raw_input('which list would you like me to print?')

I plan to have many such lists, so a series of if...then statements seems unruly.

like image 450
somefreakingguy Avatar asked Dec 28 '25 16:12

somefreakingguy


2 Answers

In the cases I can think of right now it would probably be better to have a dictionary containing what you want the user to be able to reference, for example:

my_dict = {
    'list1': ['cat', 'dog', 'juice']
    'list2': ['skunk', 'bats', 'pogo stick']
}

key = raw_input('which list would you like me to print?')

print my_dict[key]

In fact, you can take advantage of the built-in globals(), like this:

list1 = ['cat', 'dog', 'juice']
list2 = ['skunk', 'bats', 'pogo stick']
x = raw_input()

print globals()[x]

However, using globals() is almost always a bad idea, especially if it involves user input. Exposing internal variables is exceedingly questionable from a security standpoint. This is just to show that what you want is possible.

like image 163
Flávio Amieiro Avatar answered Dec 30 '25 06:12

Flávio Amieiro


The general idea of using a dict is good, but the best specific implementation is probably something like:

def pick_one(prompt, **kwds):
  while True:
    x = raw_input(prompt)
    if x in kwds:
      return kwds[x]
    else:
      print 'Please choose one of: ',
      for k in sorted(kwds):
        print k,
      print

To be used, e.g., as:

print pick_one('which list would you like me to print?',
  list1=['cat', 'dog', 'juice']
  list2=['skunk', 'bats', 'pogo stick'])

The point is that, when you're asking the user to select one among a limited number of possibilities, you'll always want to check that the choice was one of them (it is after all easy to mis-spell, etc), and, if not, prompt accurately (giving the list of available choices) and give the user another chance.

All sorts of refinements (have a maximum number of attempts, for example, after which you decide the user just can't type and pick one at random ;-) are left as (not too hard but not too interesting either ;-) exercises for the reader.

like image 40
Alex Martelli Avatar answered Dec 30 '25 04:12

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!