【问题标题】:How can i stop my python program from crashing我怎样才能阻止我的python程序崩溃
【发布时间】:2015-02-06 16:39:35
【问题描述】:

我编写了一个程序来计算一个数字的阶乘,所有这些都可以完美地工作,但是当我输入一个浮点数进行测试时会崩溃。 我的目标是接受浮点数但不计算。由于程序将接受但返回类似“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()

【问题讨论】:

  • 请修复身份
  • 查看this post,了解如何检查输入的数字是否为整数。
  • 请包括您为解决浮点问题所做的尝试,以及它是如何“崩溃”的。您是否遇到未捕获的异常?
  • 查找try/except。您应该能够尝试循环并在失败时发送消息。
  • 我可能听起来很傻,但是不能计算浮点的阶乘,对吗?所以,没有理由放 try/excepts 等

标签: python loops factorial floating


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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()
      

      【讨论】:

      • 你能补充一些解释吗?裸代码块很糟糕。
      • 模块操作符 '%' 将返回操作的剩余部分。因此,9%1 为 0,而 9.1%1 为 0.1。一旦我们确定它是否为浮点数,您就可以将其转换为 int。
      • 似乎没有必要。您应该尝试转换为 int 并在失败时捕获 ValueError。你在这里拯救自己的唯一情况是,如果用户给你一个浮点数,如果他们给你一个非数字,它将触发一个不同于裸回溯的错误消息。
      • 如果将浮点数转换为整数,它不会失败。它会截断数字。
      • 我建议 A) 转换为 float 然后转换为 int 并使用生成的整数,无论​​用户输入什么,或者 B) 不要转换为 float,因为 int("6.2") 确实失败了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多