I am learning Python and using the 3.3 version.
I have found a problem with “return” that I cannot understand.
Case 1. OK case, when “return” returns the value as expected.
def switch(a,b):
print ("inputed values:", "a is",a, ", b is",b)
if b==0:
print (a)
return a
elif b>a:
switch(b,a)
print(switch(15,0))
When executed:
inputed values: a is 15 , b is 0
15
15
Case 2. The problem case, when “return” returns “None”, though “print” prints the value.
def switch(a,b):
print ("inputed values:", "a is",a, ", b is",b)
if b==0:
print (a)
return a
elif b>a:
switch(b,a)
print(switch(0,15))
When executed:
inputed values: a is 0 , b is 15
inputed values: a is 15 , b is 0
15
None
The difference between two cases is that, in the second “elif” branch gets executed, the values get switched and the function is called again with switched values. But in the second case return is “None”.
Why in the second case it does not return the “a” value?
Add a return statement before the switch of the second if statement
The switch method returns a but the missing return statement means the value returned by the
switchstatement is not returned hence the defaultNoneis returned.