繁体   English   中英

我如何阻止我的python程序崩溃

[英]How can i stop my python program from crashing

我编写了一个程序来计算数字的阶乘,它们都可以正常运行,但是在测试中输入浮点数时崩溃。 我的目标是要接受但不计算浮点数。 程序将接受但返回诸如“错误输入,仅接受整数”之类的信息。 我已经尝试了多个语句,但是它仅适用于我在语句中输入的数字。 所以我认为也许应该建立一些东西,也许是通过命名一些浮点数并进行某种减法来实现的。 但是我迷路了。 这是我到目前为止没有包含浮动语句的程序:

    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

正如许多建议所建议的,您应该使用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将返回整数部分。

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM