Hi, today I’m sharing a recursive funtion in python. Recursive in python means the ‘def’ function to call itself. The goal is to sum up the numbers to the number I want. For example, if I put in 3:
1 + 2 + 3 = 6
# def = makes a new function
def sum(num):
# if we have an 'if', we should also have an 'else'.
if num == 0:
return 0
else:
return sum(num - 1) + num
print(sum(2))
Outcome:
3
Dats all. Bai.