且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python进行阶乘计算

更新时间:2023-02-19 23:24:38

构造可能如下所示:

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)没有任何意义,因为您无法将字符串与整数进行比较.

In Python 3, input() returns a string. You have to convert it to a number in all cases. Your N != int(N) thus makes no sense, as you cannot compare a string with an int.

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

Instead, try to convert it to an int directly, and if that doesn't work, let the user enter again. That rejects floating point numbers as well as everything else which is not valid as an integer.