How to use a function inside variable on out of function?

Asked

Viewed 36 times

-2

Past until today, I always made a mistake, I still don’t understand anything because it didn’t work. Someone can explain?

I’ll use a code example:

def test(x, y):
    if x == y:
        v1 = False
    else: 
        v1 = True
    return v1
test(3,3)
if v1 == True:
    print("OK")

Appeared like this:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-11958f52b994> in <module>
      6     return v1
      7 test(3,3)
----> 8 if v1 == True:
      9     print("OK")

NameError: name 'v1' is not defined

I tried to use "Return", but it seems that "Return" does not serve anything.

2 answers

3

You need to study better on the scope of variables (this article, for example).

Its variable v1 is created within the function test, that is, it exists only within this function.

When you do return v1 you are returning the value contained in the name variable v1, after the function closes its execution the name v1 "ceases to exist" (you cannot use it because the scope where it is valid is within the function in which it was created).

What you don’t understand yet from return is that the returned value can be used when the function is called.

In your case you could take the value returned in the function and save a variable and make the comparison you want.

Example:

resultado = test(3, 3)

if resultado:
    print('Números são diferentes.')
else:
    print('Números são iguais.')

Note that you can choose the name you want for the variable that will save the result returned by the function teste, doesn’t have to be v1.

When you better understand how the scopes of variables work you will also know the statements global and nonlocal that help you instruct the interpreter on the scope of your variables.

-1


I managed to fix your code like this I declared the variable v1 out of function, and the Return went straight to it

v1 = True

def test(x, y):
    if x == y:
        v1 = False
    else:
        v1 = True
    return v1
v1 = test(3,3)
if v1 == True:
    print("OK")
else:
    v1 = False
    print('FALSE')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.