I have code that looks similar to this
v = '0'
def program():
x = input('1 or 2 ')
if x == '1':
print('it is 1')
v = '1'
elif x == '2':
print('it is 2')
v = '2'
while True:
program()
print(v)
However, when I run this code the variable 'v' always prints out the default 0. Why isn't it giving me the variable I assigned it in the function?
You have two variables named v:
v=0 declaration at the top.v in program.First of all, you really shouldn't use globals in functions, as it is bad programming practice. You should pass it as a parameter and return with any other results.
If you really must, you can modify a global variable in a function by first declaring it as a global variable.
Also note that you need to use raw_input in Python 2.
def program():
global v
x = raw_input('1 or 2 ')
if x == '1':
print('it is 1')
v = '1'
elif x == '2':
print('it is 2')
v = '2'
Using global variables in a function other than the one that created them
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With