Python videos
Advertisement

Functions: Exercises and Solutions

Factorial using recursion

Exercise

When a function calls itself, this is called recursion. Define a factorial function that does not use a for loop, but uses recursion.

Solution

def factorial(i):

  if not i: # 0 is False
    return 1
  return i * factorial(i - 1)


print('0! == {0}'.format(factorial(0)))
print('1! == {0}'.format(factorial(1)))
print('2! == {0}'.format(factorial(2)))
print('3! == {0}'.format(factorial(3)))

Output:

0! == 1
1! == 1
2! == 2
3! == 6