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()