将用户输入设置为变量名称 [英] setting user input to variable name

查看:75
本文介绍了将用户输入设置为变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using python and would like to know if it would be possible to ask the user for the name of a variable and then create a variable with this name. For example:

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

I know it can be done using a dictionary but I would like to know whether this is possible without creating an additional object. I am using python 3. Thanks.

推荐答案

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

You can use the dictionary returned by a call to globals():

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

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

If you don't want it defined as a global variable, you can use locals():

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

这篇关于将用户输入设置为变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆