晚间,
我是一个蟒蛇学生介绍有点麻烦的介绍。我正在尝试制作一个python阶乘程序。它应该提示用户n,然后计算n的阶乘,除非用户输入-1。我很困惑,教授建议我们使用while循环。我知道我甚至没有达到'if -1'的情况。不知道怎么让python使用math.factorial函数公开地计算一个阶乘。
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)
学校中的“经典”因子函数是递归定义:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
如果你只想要一种方法来修复你的:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
如果要测试小于1的数字:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
或者,输入后测试n:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
这是使用reduce的功能方式:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800
你其实很亲密。只需每次迭代更新n
的值:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)
我是python的新手,这是我的阶乘计划。
def factorial(n):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)
阶乘(5)
你可以这样做。
def Factorial(y):
x = len(y)
number = 1
for i in range(x):
number = number * (i + 1)
print(number)