Python Factorial Example

Document 对象参考手册Python3 Examples

The factorial of an integer (English: factorial) is the product of all positive integers less than or equal to the number, and the factorial of 0 is 1. That is: n! = 1×2×3×...×n.

Example

#!/usr/bin/python3 # Filename : test.py # author by : www.example.com # Calculate factorial by taking user input number # Get the number entered by the user num = int(input("Please enter a number:")) factorial = 1 # Check if the number is negative, 0, or positive if num < 0: print("Sorry, negative numbers have no factorial") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of %d is %d" %(num,factorial))

The output after executing the above code is:

请输入一个数字: 3
3 的阶乘为 6

Document 对象参考手册Python3 Examples

Other Extensions