Creating Python Factorial

99封情书 提交于 2019-12-02 17:19:41

问题


Evening,

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)

回答1:


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

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

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



回答2:


You are actually very close. Just update the value of n with each iteration:

num = 1
n = int(input("Enter n: "))

while n >= 1:
    num *= n
    # Update n
    n -= 1
print(num)



回答3:


I am new to python and this is my factorial program.

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)

factorial(5)




回答4:


You could do something like this.

    def Factorial(y):
        x = len(y)
        number = 1
        for i in range(x):
            number = number * (i + 1)
            print(number)


来源:https://stackoverflow.com/questions/19107715/creating-python-factorial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!