python 数字的阶乘_Python | 查找给定数字的阶乘(2种不同方式)

python 数字的阶乘

Given a number and we have to find its factorial in Python.

给定一个数字,我们必须在Python中找到其阶乘。

Example:

例:

    Input:
    Num = 4

    Output:
    Factorial of 4 is: 24

1)方法1:使用循环 (1) Method 1: Using loop)

# Code to find factorial on num

# number
num = 4

# 'fact' - variable to store factorial 
fact =1 

# run loop from 1 to num
# multiply the numbers from 1 to num
# and, assign it to fact variable 

for i in range (1,num+1) :
	fact = fact*i 

# print the factorial
print "Factorial of {0} is: {1} ".format (num, fact)

Output

输出量

    Factorial of 4 is: 24 

2)方法2:通过使用递归方法创建函数 (2) Method 2: by creating a function using recursion method)

To find the factorial, fact() function is written in the program. This function will take number (num) as an argument and return the factorial of the number.

为了找到阶乘,在程序中编写了fact()函数。 此函数将数字(num)作为参数,并返回数字的阶乘。

# function to calculate the factorial 
def fact (n):
	if n == 0:
		return 1 
	return n * fact (n - 1)

# Main code 
num = 4

# Factorial
print "Factorial of {0} is: {1} ".format (num, fact(num))

Output

输出量

    Factorial of 4 is: 24 


翻译自: https://www.includehelp.com/python/find-factorial-of-a-given-number.aspx

python 数字的阶乘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值