How to get the value of a variable entered from user input?

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

Example.

Item1 = "bill" Item2 = "cows" item3 = "abcdef" Choose_Item = input("Select your item: ") 
  • I type Item1
  • Choose_Item should equal "bill"
+8
source share
3 answers

This is similar to what you are looking for:

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

This is probably not the best strategy, because a typo or a malicious user can easily crash your code, overload your system, or do any other unpleasant things that they like. In this particular case, the best 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") 
+20
source

There are two ways to do this. Bad way

 print(eval(Choose_Item)) 

It would be best 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) 
+4
source

You will need to use locals()[Choose_Item] if you want to select a variable whose name was created by the user.

A more common way to do this, however, is to use a dictionary:

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

... and then the required value of items[Choose_Item] .

+4
source

All Articles