Home > Backend Development > Python Tutorial > How to write factorial in python

How to write factorial in python

藏色散人
Release: 2019-08-01 15:49:21
Original
16536 people have browsed it

How to write factorial in python

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

How to write factorial in python?

Example

#!/usr/bin/python3
 
# Filename : test.py

 
# 通过用户输入数字计算阶乘
 
# 获取用户输入的数字
num = int(input("请输入一个数字: "))
factorial = 1
 
# 查看数字是负数,0 或 正数
if num < 0:
   print("抱歉,负数没有阶乘")
elif num == 0:
   print("0 的阶乘为 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("%d 的阶乘为 %d" %(num,factorial))
Copy after login

The output result of executing the above code is:

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

Related recommendations: "Python Tutorial"

The above is the detailed content of How to write factorial in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template