-2

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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38

3 Answers3

2

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.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
0

Python and many other languages have a concept of "falsy", which roughly means "values that are treated as False when evaluated as a boolean". In Python, values that are falsy include empty collections such as empty lists, strings, sets, tuples, and dicts, the int or float 0, and None. I may be missing some here, and you may find that some classes are designed to be treated as falsy as well under certain conditions. There are also "truthy" values which evaluate to True is a boolean context. It's easy to find out if a value is truthy or falsy. Simply call bool() on it:

bool(0.0)
# False

In the context of your code, when 0 is reached, that will be evaluated as falsy, triggering the exit condition.

DragonBobZ
  • 2,194
  • 18
  • 31
-1

if num: means if num is different than 0 : if num!=0. you better remove the else statement. def addition(num): if num: return num + addition(num - 1) return 0

python already knows that return is an else statement.

here's a playlist of one of the bests on youtube by corey to learn & become at python : https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7

and also I recommend this book, automating the boring stuff with python. it's free : https://automatetheboringstuff.com/

neotrix
  • 47
  • 5