Question

I want to re-assign the value of a variable chosen by the user. The idea is that, if the user chooses this variable, the value of that variable is set to zero.

The code looks like this:

v1 = 8.4
v2 = 12.1
v3 = 36.2

list = ['', 'v1=', 'v2=', 'v3=']

print("What v do you want to be zero?")
print("    1 = v1")
print("    2 = v2")
print("    3 = v3")
a = eval(input("Enter your choice: "))

(the user enters 1)

b = list[a] + '0'
exec(b)
print(v1, v2, v3)

When I enter this code in IDLE, line by line, I get:

0 12.1 36.2

But, when I run the identical code within a function (*so the exec() and print(v1,v2,v3) statements are inside the same function), I get:

8.4 12.1 36.2

Can anyone explain this? I think it's probably a terrible way to do what I'm doing (I'm new to coding), and I welcome your suggestions on how to do it better, maybe a loop or a series of 'if/elif' statements? However, what I'd really like to know is why this code works when it's entered line-by-line, but not as a function.

(* = edit)

This is a program that does not re-assign any variable:

# delete me.py

def main():

    v1 = 8.4
    v2 = 12.1
    v3 = 36.2

    list = ['', 'v1=', 'v2=', 'v3=']

    print("What v do you want to be zero?")
    print("    1 = v1")
    print("    2 = v2")
    print("    3 = v3")
    a = eval(input("Enter your choice: "))

    b = list[a] + '0'
    exec(b)

    print(v1, v2, v3)

main()
Was it helpful?

Solution

The easiest way to understand this is that you aren't allowed to modify variables through exec. It will sometimes work, but its not really allowed, and its never a good idea.

For this piece of code, you should write:

v = [8.4, 12.1, 36.2]
print("What v do you want to be zero?")
print("    1 = v1")
print("    2 = v2")
print("    3 = v3")
a = int(input("Enter your choice: "))
v[a - 1] = 0
print(v)

Basically, if you need to lookup a variable by user input, it should be in a list or dictionary. You should never need to do this for local variables.

OTHER TIPS

This is because you are updating the local scope of the function inside which you exec is run.

Compare this:

v = 42
def f(): v = 43 #which is inside you exec
f()
print(v)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top