Python videos
Advertisement

Functions: Exercises and Solutions

Factorial using for

Exercise

The factorial (!) of a positive integer number is the product of all numbers from 1 up to and including the number itself. So 3! == 3 × 2 × 1. By convention, 0! == 1. The factorial of negative numbers is undefined.

Define a function that takes a number as an argument, and returns the factorial for that number. The function can assume that the input is a non-negative integer. Use a for loop inside the function.

Solution

def factorial(i):

  f = 1
  for j in range(i):
    f *= j + 1
  return f


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