简体   繁体   English

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

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

I wrote a program to calculate the factorial of a number all work perfectly but crashes when for test I enter a float number. 我编写了一个程序来计算数字的阶乘,它们都可以正常运行,但是在测试中输入浮点数时崩溃。 My goal is for a floating number to be accepted but not calculated. 我的目标是要接受但不计算浮点数。 As the program will accept but return something like "Bad entry, only integers are accepted." 程序将接受但返回诸如“错误输入,仅接受整数”之类的信息。 I have tried multiple statement but it only work for the number I put in the statement. 我已经尝试了多个语句,但是它仅适用于我在语句中输入的数字。 So I thought maybe something should be built, maybe by naming some floats and doing some sort of subtraction. 所以我认为也许应该建立一些东西,也许是通过命名一些浮点数并进行某种减法来实现的。 But I get lost. 但是我迷路了。 here is the program I have so far without the floating statement included: 这是我到目前为止没有包含浮动语句的程序:

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

You should use a try/catch block, since int('3.2') (or any other float string) will raise an error. 您应该使用try / catch块,因为int('3.2') (或任何其他浮点字符串)将引发错误。 For example: 例如:

try: num = int(input('Enter a number...'))
except ValueError:
   print 'We only accept integers.'
   return

As many have suggested, you should use a try/except block. 正如许多建议所建议的,您应该使用try/except块。 However if you want to accept user input like "6.12" and just calculate from the integer part, you should do: 但是,如果要接受"6.12"类的用户输入并仅从整数部分进行计算,则应该执行以下操作:

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

int cannot operate on a string that's not integer-like, but it CAN operate on a floating point number. int不能对非整数形式的字符串进行运算,但是可以对浮点数进行运算。 Calling float on the string will give you a floating point number, and calling int on that floating point number will return the integer part. 在字符串上调用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.

相关问题 有什么方法可以阻止python程序崩溃吗? - Is there any method to stop python program from crashing? 如何在标准化图像时阻止我的 Colab 笔记本崩溃? - How can I stop my Colab notebook from crashing while normalising my images? 如何阻止我的程序生成相同的密钥? - How can I stop my program from generating the same key? 如何防止我的Selenium / Python程序崩溃? - How to prevent my Selenium/Python program from crashing? 当输入字母代替数字时,如何防止程序崩溃? - How do I stop the program from crashing when given a letter in the place of a number? 如何从我的 python 程序中调用智能合约? - how can I call smart contract from my python program? 在 Python 上没有询问任何问题时,如何阻止我的 Magic 8 Ball 程序生成随机数? - How do I stop my Magic 8 Ball Program from generating a random number when no question is asked on Python? 如何在每次重新运行程序时停止openpyxl-python清除我的excel文件? - How to stop openpyxl - python from clearing my excel file every time I re-run the program? 如何让 Python 程序从终端连续运行(直到我手动停止它)? - How can I make a Python program run continuously from the Terminal (until I stop it manually)? 如何在后台调度程序运行时阻止程序崩溃? - How to stop program from crashing while background scheduler is running?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM