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

Python basic tutorial

Python flow control

Fonction 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 to calculate the factorial of a number

Python complete examples

In this article, you will learn to find the factorial of a number and display it.

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

The factorial of a number is1is the product of all integers up to that number.

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

Source code

# Python program to find the factorial of the number provided by the user.
# Can be changed to a different value
num = 7
# Get input from the user
#num = int(input("Enter number: "))
factorial = 1
# Check if the number is negative, positive, or zero
if num < 0:
   print("Sorry, there is no factorial for negative numbers")
elif num == 0:
   print("0's factorial is"1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print(num, "The factorial is", factorial)

Output result

7 The factorial is 5040

Note:To test the program with other numbers, please change the value of num.

Here, the number whose factorial is to be found is stored in num, and then the if...elif...else statement is used to check whether the number is negative, zero, or positive. If the number is positive, the factorial is calculated using a for loop and the range() function.

Python complete examples