Search code examples
pythonpython-3.xconsoleglobal-variables

Using console to choose and change a global variable in Python


I'm learning python and trying to use a function to choose and change a global variable.

I want to use the console to choose which variable to change and then choose the new value.

I'm using global inside the function to access the variables and I'm using exec() to proceed with the desired modification captured through input(). But something is not working.

Can someone please figure out what is wrong here?

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

Solution

  • The exec() uses globals() and locals() as defaults for their global and local variables. It defaults to changes in the locals(), not the globals. You therefore have to explicitly tell it to overwrite globals. You can do this the following way:

    exec(something + " = '" + new_value + "'", globals())