Python confusion with return variables

There is something I don’t understand here when it comes to returned variables. For simplicity, I wrote a really basic thing to summarize the problem I have:

def apples():
    dingo = 2
    return dingo

def bananas(dingo):
    print(dingo)

def main():
    apples()
    bananas(dingo)

main()

So, I create "dingo" in the "apples" function. I am returning it. I use it as a parameter in bananas. I call them as basically, so why am I getting the error that "dingo" is undefined? Also, something that I cannot do is put dingo = apples()inside the banana function. I cannot unpack it inside the banana function, because I want to name them mostly individually. Is there any way around this without unpacking?

+4
5

, apples() -, dingo main(). :

def apples():
    dingo = 2
    return dingo

def bananas(dingo):
    print(dingo)

def main():
    result = apples()
    bananas(result)

main()

, result - , bananas() - ​​ , .

def bananas(dingo) : bananas, . bananas() dingo.

, bananas(), .

: dingo, 2 - , , - (2), , .

+2

, , , .

, NameError: global name 'dingo' is not defined ?

In [38]: def apples():
    ...:     dingo = 2
    ...:     return dingo
    ...: 
    ...: def bananas(dingo):
    ...:     print(dingo)
    ...: 
    ...: def main():
    ...:     dingo=apples()
    ...:     bananas(dingo)
    ...: 
    ...: main()
2
0
def apples():
    dingo = 2
    return dingo

def bananas(dingo):
    print(dingo)

def main():
    apples()
    bananas(dingo)

main()

dingo apples(), ( ) , . , dingo .

apples() dingo, bananas() main(), dingo apples()

:

def ret_val():
    var=5
    return var
main()
    x=ret_val
    print x
Output:
5

return , . :

def apples():
    dingo = 2
    return dingo

def bananas(dingo):
    print(dingo)

def main():
    x=apples()#here x will store the value of dingo i.e 2
    bananas(x)#the value of x will be passed

main()

, -, return , (.. )

def check(x):
   if (x % 2==0):
      return "even"
   return "odd"

return, , return . - break , .

0

, :

, , :

def apples():
    dingo = 2
    return dingo

def bananas(another_name):
    print(another_name)

def main():
    result = apples()
    bananas(result)

main()

, bananas, .

0

In the function definition, mainchange the code to look like this

def main():  
   bananas(apples())  

This way you avoid temporarily assigning return values

0
source

Source: https://habr.com/ru/post/1526039/


All Articles