使用Python进行因子计算

use*_*seR 6 python factorial python-3.x

我是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)
Run Code Online (Sandbox Code Playgroud)

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

if N != int(N) and N < 0:
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的温柔帮助.

glg*_*lgl 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.")
Run Code Online (Sandbox Code Playgroud)

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

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