从用户输入创建动态命名变量的Python程序
给定一个字符串输入,任务是编写一个Python程序来从该输入创建一个变量(作为变量名)并为其分配一些值。以下是从用户输入创建动态命名变量的方法:
方法一:使用 globals() 方法。
Python3
# Dynamic_Variable_Name can be
# anything the user wants
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
globals()[Dynamic_Variable_Name] = 2020
# Display variable
print(geek)
Python3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
locals()[Dynamic_Variable_Name] = 2020
# Display variable
print(geek)
Python3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
exec("%s = %d" % (Dynamic_Variable_Name, 2020))
# Display variable
print(geek)
Python3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
vars()[Dynamic_Variable_Name] = 2020
# Display variable
print(geek)
输出:
2020
方法 2:使用 locals() 方法。
蟒蛇3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
locals()[Dynamic_Variable_Name] = 2020
# Display variable
print(geek)
输出:
2020
方法 3:使用 exec() 方法。
蟒蛇3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
exec("%s = %d" % (Dynamic_Variable_Name, 2020))
# Display variable
print(geek)
输出:
2020
方法 4:使用 vars() 方法
蟒蛇3
# Dynamic_Variable_Name can be
# anything the user wants.
Dynamic_Variable_Name = "geek"
# The value 2020 is assigned
# to "geek" variable
vars()[Dynamic_Variable_Name] = 2020
# Display variable
print(geek)
输出:
2020