10

I am trying to create a basic menu that checks to see if the variable entered matches a defined variable. If the variable is defined get the data of the defined variable.

Example.

Item1 = "bill"
Item2 = "cows"
item3 = "abcdef"
Choose_Item = input("Select your item: ")
  • I type in Item1
  • Choose_Item should equal "bill"
martineau
  • 119,623
  • 25
  • 170
  • 301
Nick W.
  • 1,536
  • 3
  • 24
  • 40

3 Answers3

23

This seems like what you're looking for:

Choose_Item = eval(input("Select your item:  "))

This probably isn't the best strategy, though, because a typo or a malicious user can easily crash your code, overload your system, or do any other kind of nasty stuff they like. For this particular case, a better approach might be

items = {'item1': 'bill', 'item2': 'cows', 'item3': 'abcdef'}
choice = input("Select your item: ")
if choice in items:
    the_choice = items[choice]
else:
    print("Uh oh, I don't know about that item")
Danica
  • 28,423
  • 6
  • 90
  • 122
4

Two ways you could go about this. The bad way:

print(eval(Choose_Item))

The better way would be to use a dictionary

items = {'1':'bill','2':'cows'}
Choose_Item = input("Select your Item: ")
try:
    print(items[Choose_Item])
except KeyError:
    print('Item %s not found' % Choose_Item)
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
Dave Lasley
  • 5,262
  • 1
  • 34
  • 37
  • 3
    FWIW: question is tagged python-3, so you'd want parens in that print statement, and you probably also want to print something in the exception case rather than just building a string and not doing anything with it. :) – Danica Mar 01 '13 at 23:50
  • But aren't random strings good programming etiquette? Good catch sir, another reason why you deserve this answer – Dave Lasley Mar 01 '13 at 23:52
4

You'll need to use locals()[Choose_Item] if you want to choose a variable whose name is what the user produced.

A more conventional way to do this, though, is to use a dictionary:

items = {
    'Item1': 'bill',
    'Item2': 'cows',
    'Item3': 'abcdef',
}

... and then the value you want is items[Choose_Item].

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • +1 - the locals approach is better than eval, in that it at least doesn't let a malicious user go and, well, evaluate code. :) Of course the dictionary approach is preferable. – Danica Mar 01 '13 at 23:55