Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable from a defined function in a while loop [duplicate]

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?

like image 569
Jopplk Avatar asked Sep 28 '26 01:09

Jopplk


1 Answers

You have two variables named v:

  1. The global level v=0 declaration at the top.
  2. The function declaration of 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

like image 125
Alexander Avatar answered Sep 30 '26 17:09

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!