Search code examples
pythoncode-readability

Explain this if-else condition in Python


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?


Solution

  • if variable: and truthyiness

    See 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:

    • is defined: num is not None
    • and is not zero: num != 0

    bool(0) is False. The opposite condition is tested by if not num.

    The role of if in a recursive function

    It'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:

    Edge-cases for input

    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.