Python 如何获取从用户输入中输入的变量的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15168765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:30:25  来源:igfitidea点击:

How to get value of variable entered from user input?

pythonpython-3.x

提问by Nick W.

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_Itemshould equal "bill"
  • 我输入 Item1
  • Choose_Item应该等于 "bill"

采纳答案by Dougal

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")

回答by Dave Lasley

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)

回答by Borealid

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

你需要使用locals()[Choose_Item],如果你想选择一个变量,其名称是用户产生的内容。

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

...然后你想要的值是items[Choose_Item].