Home > Mobile >  Print returns of two conditions in the same function?
Print returns of two conditions in the same function?

Time:04-03

Why do I print only the return of the first condition and not the second? I want to print them both. How can I print the return of the first and second condition at the same time?

I would get output "yes1" e "no2", and i would use individually them and recall them.

def a():
    
   if 2 > 1:
       print("yes 1")
       variable_1 = yes1
       return variable_1
   else:
       variable_2 = no1
       print("no 1")       
       return variable_2


   if 3 < 2:
       variable_3 = yes2
       print("yes 2")
       return variable_3
   else:
       variable_4 = no2
       print("no 2")       
       return variable_4

a()

CodePudding user response:

You can certainly return multiple things, but you have to gather them up and return them in one statement.

def a():
   togo = []    
   if 2 > 1:
       print("yes 1")
       variable_1 = yes1
       togo.append('yes1')
   else:
       variable_2 = no1
       print("no 1")       
       togo.append('no1')

   if 3 < 2:
       variable_3 = yes2
       print("yes 2")
       togo.append('yes2')
   else:
       variable_4 = no2
       print("no 2")       
       togo.append('no2')

   return togo

print(a())

CodePudding user response:

You can use dictionary to save the values of each variables and use it further.

def a():
   result = {}  
   if 2 > 1:
       print("yes 1")
       result['variable_1'] = 'yes1'
   else:
       print("no 1")
       result['variable_2'] = 'no1'

   if 3 < 2:
       print("yes 2")
       result['variable_3'] = 'yes2'
   else:
       print("no 2")
       result['variable_4'] = 'no2' 

   return result

result = a()

If yes1 yes2 no1 no2 are just strings

def a():
    result = {}  
    if 2 > 1:
       print("yes 1")
       result['variable_1'] = 'yes1'
    else:
       print("no 1")
       result['variable_2'] = 'no1'
    if 3 < 2:
       print("yes 2")
       result['variable_3'] = 'yes2'
    else:
       print("no 2")
       result['variable_4'] = 'no2'
    return result

result = a()

And then if you need value of variable_1 you can do so by:

print (result['variable_1'])

And so on....

  • Related