我正在学习python,并尝试使用一个函数来选择和更改全局变量。
我想使用控制台来选择要更改的变量,然后选择新的值。
我在函数中使用global
来访问变量,并使用exec()
来继续通过input()
捕获所需的修改。但有些东西不起作用。
有人能找出这里出了什么问题吗?
name = "John"
age = 45
gender = "male"
def identify_yourself():
print("My name is " + name + ".")
print("I'm " + str(age) + " years old.")
print("I'm " + gender + ".")
def change_something():
global name, age, gender
something = input("Which variable do you want to change?n> ")
# I then input "name"
new_value = input("Change to what?n> ")
# I Then input "Paul"
exec(something + " = '" + new_value + "'")
identify_yourself()
identify_yourself()
# This first prints...
#
# My name is John.
# I'm 45 years old.
# I'm male.
change_something()
# On the second time this SHOULD print...
#
# My name is Paul.
# I'm 45 years old.
# I'm male.
#
# ... but it's not working.
# It keeps printing "My name is John" even after I run the change_something() function
exec()
使用globals()
和locals()
作为全局和局部变量的默认值。它默认为locals()
中的更改,而不是全局更改。因此,您必须明确地告诉它覆盖全局变量。你可以通过以下方式做到这一点:
exec(something + " = '" + new_value + "'", globals())