0

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?

2
  • How can you ? The scope is different ;) Commented Apr 26, 2016 at 8:09
  • You only return one value from myfunction, the others are inaccessible. Commented Apr 26, 2016 at 8:10

5 Answers 5

7

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)
Sign up to request clarification or add additional context in comments.

Comments

4

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)

1 Comment

Nitpicking: In fact you only return one value from the function. This value is a tuple with two elements which is unpacked to two variables in the while loop.
3

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

Comments

1

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)

Comments

1

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.