使用Python进行因子计算

问题描述 投票:6回答:4

我是Python新手,目前正在阅读Python 3的绝对初学者和面对以下问题。

我想用程序计算阶乘。

  1. 请求用户输入非负数n
  2. 然后使用for循环来计算阶乘

而代码是这样的:

N = input("Please input factorial you would like to calculate: ")
ans = 1
for i in range(1,N+1,1):
    ans = ans*i
print(ans)

而我想添加一项功能来检查输入数字N是否为非负数。喜欢:

if N != int(N) and N < 0:

我希望用户再次输入N,如果它不是非负数。

谢谢你的温柔帮助。

python python-3.x factorial
4个回答
4
投票

构造可能如下所示:

while True:
    N = input("Please input factorial you would like to calculate: ")
    try: # try to ...
        N = int(N) # convert it to an integer.
    except ValueError: # If that didn't succeed...
        print("Invalid input: not an integer.")
        continue # retry by restarting the while loop.
    if N > 0: # valid input
        break # then leave the while loop.
    # If we are here, we are about to re-enter the while loop.
    print("Invalid input: not positive.")

在Python 3中,input()返回一个字符串。在所有情况下,您都必须将其转换为数字。因此你的N != int(N)毫无意义,因为你无法将字符串与int进行比较。

相反,尝试直接将其转换为int,如果不起作用,请让用户再次输入。这会拒绝浮点数以及其他无效的整数。


1
投票

在Python数学库中,有一个阶乘函数。您可以像这样使用它:

import math
...
ans = math.factorial(N)

既然您想使用循环计算,您是否考虑过以下内容?

ans = -1
while ans < 0:
    N = input("Please enter a positive integer: ")
    if N.isdigit() == True:
        n = int(N)
        if n >= 0:
            ans = n
            for x in range (n-1, 1, -1):
                ans *= x
            print (ans)

注意,第二种解决方案不适用于N = 0,其中ans = 1通过阶乘的定义是正确的。


0
投票
Number = int(input("Enter the number to calculate the factorial: "))
factorial = 1
for i in range(1,Number+1):
    factorial = i*factorial

print("Factorial of ",Number," is : ", factorial)

0
投票

你可以检查python的数学模块。

math.factorial(x)

返回x阶乘。如果x不是整数或为负,则引发ValueError。

© www.soinside.com 2019 - 2024. All rights reserved.