English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program uses recursion to calculate the factorial of a number

Python complete examples

In this program, you will learn to use recursive functions to calculate the factorial of a number.

To understand this example, you should understand the followingPython programmingTopic:

The factorial of a number is from1is the product of all integers up to the number.

For example, the factorial6is1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers, the factorial of zero is1、0!= 1.

Source code

# Python program uses recursion to calculate the factorial of a number
def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)
num = 7
# Check if the number is negative
if num < 0:
   print("Sorry, the factorial of negative numbers does not exist")
elif num == 0:
   print("The factorial of 0 is ",1")
else:
   print(num, "'s factorial is", recur_factorial(num))

Output result

7 The factorial is 5040

Note:To find the factorial of other numbers, change the value of num.

Here, the number is stored in num. This number will be passed to the recur_factorial() function to calculate the factorial of the number.

Python complete examples