English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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 this 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.
# 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, "The factorial is", recur_factorial(num))
Output result
7 The factorial is 5040
Note:To find the factorial of other numbers, please 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.