How to get value of variable entered from user input?

前端 未结 3 1665
余生分开走
余生分开走 2020-12-06 02:53

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.

相关标签:
3条回答
  • 2020-12-06 02:58

    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].

    0 讨论(0)
  • 2020-12-06 03:19

    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)
    
    0 讨论(0)
  • 2020-12-06 03:22

    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")
    
    0 讨论(0)
提交回复
热议问题