简体   繁体   中英

Python access variable in while loop

I have this simple Python 3 script

def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current

current = 1
while ( current < 10 ):
    current = myfunction(current)

It works great but I am trying to use the myvalue variable in the while loop. How can I get access to the variable?

You'll have to return myvalue if you want to use it.

def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current, myvalue

current = 1
while ( current < 10 ):
    current, myvalue = myfunction(current)
    print(myvalue)

You can return multiple variables from a function

Try with the below code:

def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current, myvalue

current = 1
while ( current < 10 ):
    current, myvalue = myfunction(current)

myvalue variable is local to the method myfunction . You can't access it outside that method.

You may either

  • use a global variable, or
  • return value from myfunction

you have 2 ways:

1: make the variable global:

myvalue = 'initvalue'

def myfunction(current):
    global myvalue 
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current

current = 1
while ( current < 10 ):
    current = myfunction(current)

2: return multiple variables from your function function

def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current, myvalue

current = 1
while ( current < 10 ):
    current, myvalue = myfunction(current)

In case you wanted all the values inside the function with the same identities, you could also try this (but do ensure you are not using the same variable names outside, which kinda destroys the purpose)

def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    return locals()

which should give you a dictionary of the variables. The output for print myfunction(1) will be

{'current': 2, 'myvalue': 'Test Value'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM