创建Python阶乘 [英] Creating Python Factorial
问题描述
晚上
我是遇到麻烦的python学生的简介. 我正在尝试制作python阶乘程序.它应该提示用户输入n,然后计算n的阶乘,除非用户输入-1.我很困惑,教授建议我们使用while循环.我知道我什至还没有达到'if -1'的情况.不知道如何让python仅仅使用math.factorial函数就可以计算出阶乘.
I'm an intro to python student having some trouble. I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)
推荐答案
学校中的经典"阶乘函数是一个递归定义:
The 'classic' factorial function in school is a recursive definition:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
如果您只想找到一种解决方法:
If you just want a way to fix yours:
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的数字,
If you want a test for numbers less than 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:
Or, test n after input:
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
这是使用减少的功能性方式:
Here is a functional way using reduce:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800
这篇关于创建Python阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!