def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
I know what the function is doing:
I just don't know what if num:
means or the else part.
I am guessing it means as long as the num
is int do what is inside the if, else return 0.
Can someone tell me what this code means?
if variable:
and truthyinessSee the boolean values and Python's Truth Value Testing:
You can evaluate truthy and falsy values using the bool()
conversion-function:
print('None:', bool(None))
print('zero:', bool(0))
print('negative:', bool(-1))
print('positive:', bool(1))
if num:
mets if num
is defined and unequal to 0:
num is not None
num != 0
bool(0)
is False. The opposite condition is tested by if not num
.
if
in a recursive functionIt's a recursive function which calls itself until exit-condition num == 0
is met in the else
branch. Then it simply returns 0. So, the role of if num:
is the continue-condition opposed to an exit-condition.
You could also write it as exit-condition:
def addition(num):
if not num: # equivalent to: if num == 0 or num is None
return 0 # return 0 if exit-condition met
# default behavior: recurse until zero met
return num + addition(num - 1)
See also:
Note, how input of None
and other falsy values return a zero.
Please also consider the edge-case of negative input, as Fred commented. Could (silently) return 0 to abort addition. Also might raise an error to warn about misuse, like:
if num < 0:
raise ValueError("Can not calculate the recursive-sum for negative values.")
What happens if a float like 10.5
is given as input?
It would step through each -1 decrease until 0.5
. The next call of addition(-0.5)
would jump over the num == 0
exit-condition and cause infinite recursion, even a stackoverflow.