如何获取从用户输入中输入的变量的值? [英] How to get value of variable entered from user input?
本文介绍了如何获取从用户输入中输入的变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个基本菜单,用于检查输入的变量是否与定义的变量匹配.如果定义了变量,则获取定义变量的数据.
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.
示例.
Item1 = "bill"
Item2 = "cows"
item3 = "abcdef"
Choose_Item = input("Select your item: ")
- 我输入
Item1
Choose_Item
应该等于"bill"
- I type in
Item1
Choose_Item
should equal"bill"
推荐答案
这似乎是您要找的:
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")
这篇关于如何获取从用户输入中输入的变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文