python - 将用户输入设置为变量名

标签 python

<分区>

我正在使用 python,想知道是否可以向用户询问变量的名称,然后使用该名称创建一个变量。例如:

my_name = input("Enter a variable name") #for example the user could input orange
#code to set the value of my_name as a variable, say set it to the integer 5
print(orange) #should print 5 if the user entered orange

我知道可以使用字典来完成,但我想知道这是否可以在不创建额外对象的情况下实现。我正在使用 python 3。谢谢。

最佳答案

您可以使用通过调用 globals() 返回的字典:

input_name = raw_input("Enter variable name:") # User enters "orange"
globals()[input_name] = 4
print(orange)

如果不想定义为全局变量,可以使用locals():

input_name = raw_input("Enter variable name:") # User enters "orange"
locals()[input_name] = 4
print(orange)

关于python - 将用户输入设置为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824194/

相关文章:

python - 下面的二次方程代码有什么问题?

python - 使用函数接受不是标识符的 kwargs 关键字参数是否安全?

python - 模拟一个类并返回几个值

python - 将稀疏的 NER 实体标签移至顶部或底部

python - 如何根据索引在日期间隔之间的条件过滤数据框?

python - 导入错误 : cannot import name _args_from_interpreter_flags

python - 防止 TextIOWrapper 以 Py2/Py3 兼容的方式关闭 GC

python - Tornado 上下文管理器在 gen.coroutine 中调用

需要 Python Regex 帮助

python - 对自定义容器对象进行排序