Code
def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
Explanation
I know what the function is doing:
- it is a recursive function
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.
Question
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:if num:mets ifnumis defined and unequal to 0:num is not Nonenum != 0bool(0)is False. The opposite condition is tested byif not num.The role of
ifin a recursive functionIt's a recursive function which calls itself until exit-condition
num == 0is met in theelsebranch. Then it simply returns 0. So, the role ofif num:is the continue-condition opposed to an exit-condition.You could also write it as exit-condition:
See also:
Edge-cases for input
Note, how input of
Noneand 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:
What happens if a float like
10.5is given as input? It would step through each -1 decrease until0.5. The next call ofaddition(-0.5)would jump over thenum == 0exit-condition and cause infinite recursion, even a stackoverflow.