我怎样才能阻止我的 python 程序崩溃

How can i stop my python program from crashing

我编写了一个程序来计算一个数字的阶乘,所有这些都运行得很好,但是当我输入一个浮点数进行测试时崩溃了。 我的目标是接受但不计算浮点数。因为程序会接受但是 return 类似 "Bad entry, only integers are accepted." 我尝试了多个语句,但它只适用于我在语句中输入的数字。所以我想也许应该构建一些东西,也许通过命名一些浮点数并进行某种减法。但是我迷路了。 这是我到目前为止没有包含浮动语句的程序:

    def main():
# take input from the user
        num = int(input("Enter a number: "))
        factorial = 1
        if num > 100:
            print("Bad entry. It should be an integer less than or equal to 100!")
            print("Please try again: ")
        elif num == 0:
            print("The factorial of 0 is 1")
        elif num < 0:
            print("Bad entry. It should be an integer superior than or equal to 0!")
            print("Please try again: ")  
        else:
            for i in range(1,num + 1):
                factorial = factorial*i
            print("The factorial of",num,"is",factorial)

main()

您应该使用 try/catch 块,因为 int('3.2')(或任何其他浮点字符串)会引发错误。例如:

try: num = int(input('Enter a number...'))
except ValueError:
   print 'We only accept integers.'
   return
def main():
    # take input from the user
    num = float(input("Enter a number: "))
    if (num%1 != 0):
        print("Bad entry, only integers are accepted.")
        return 

    num = int(num)
    factorial = 1
    if num > 100:
        print("Bad entry. It should be an integer less than or equal to 100!")
        print("Please try again: ")
    elif num == 0:
        print("The factorial of 0 is 1")
    elif num < 0:
        print("Bad entry. It should be an integer superior than or equal to 0!")
        print("Please try again: ")  
    else:
        for i in range(1,num + 1):
            factorial = factorial*i
        print("The factorial of",num,"is",factorial)

main()

正如许多人所建议的那样,您应该使用 try/except 块。但是,如果你想接受像 "6.12" 这样的用户输入并且只从整数部分计算,你应该这样做:

user_in = "6.12" # or whatever the result from the input(...) call is
user_in = int(float(user_in)) # 6

int 不能对不是整数的字符串进行操作,但它可以对浮点数进行操作。在字符串上调用 float 会给你一个浮点数,在那个浮点数上调用 int 会 return 整数部分。