0

I have the following simple code to compute the sum of values until the indicated number. The total is stored inside result.

def ComputeMath(number, result):
   if number > 0:
       result = number + result
       print('if', result)
       ComputeMath(number-1, result)
   else:
       print("else", result)
       return result;

output = ComputeMath(5,0)
print(output)

For some reason output is always None. Printing it inside the function works fine. I just cannot figure out why this is happenning. Here is the output:

enter image description here

renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

1

The conditional split the code flow/execution among two paths but only one of them has a return, hence the other one will implicitly return None

def ComputeMath(number, result):
   if number > 0:
       result = number + result
       print('if', result)
       return ComputeMath(number-1, result)
   else:
       print("else", result)
       return result

output = ComputeMath(5,0)
print(output)

Here another possibility, a return for "all":

def ComputeMath(number, result):
   if number > 0:
       result = number + result
       print('if', result)
       ComputeMath(number-1, result)
   else:
       print("else", result)
   return result

Another way to look at the problem is not to print the output since the print is already in the body of the function.

def ComputeMath(...): # as in the question
   ....

output = ComputeMath(5,0) # the output maybe None
if output is not None:
    print(output)
cards
  • 3,936
  • 1
  • 7
  • 25