【问题标题】:Implementing ZeroDivisionError exception in python在 python 中实现 ZeroDivisionError 异常
【发布时间】:2017-03-22 00:23:25
【问题描述】:

所以,在编程方面,我是一个完全的菜鸟,周末才开始学习 python。无论如何,作为 Youtube 教程之一的挑战,我想编写一个程序,可以找到定义范围内的所有数字,当除以 4 时会给我 0 提醒,然后它们将被列出。所以我更进一步,下面是我到目前为止所得到的。

# Program that let's you find all numbers in any range defined by user
# that can be divided without any reminder by the number also defined by user

print('Find all numbers in range...')

while True:
    try:
        x = int(input('From: ')) # begining of the range
        y = int(input('.. to: ')) # end of the range
        z = int(input('.. that can be divided by: ')) # value of the number to divide by
    except ValueError: # in case of a nonint input
        print('You should enter a valid number!')
        continue

    for a in range(x, y):
        try:
            if a % z == 0:
                print(a, [a / z], end = ' ') 
        except ZeroDivisionError: # issue with implementing this exception
            pass

我不使用 pass 语句,而是尝试这样做

print('You can\'t divide by 0!!') # or similar

它打印字符串 (x, y) 次。有什么建议么?非常感谢提前

【问题讨论】:

  • 我已经尝试了您建议的方案并且它工作正常,但其他方式似乎没有做......没有,程序以代码 0 终止,没有返回任何值......

标签: python pycharm divide-by-zero


【解决方案1】:

问题是您在 for 循环中尝试/排除。如果您不希望程序在遇到异常时终止,只需在打印警告后中断循环即可。

print('Find all numbers in range...')

while True:
    try:
        x = int(input('From: ')) # begining of the range
        y = int(input('.. to: ')) # end of the range
        z = int(input('.. that can be divided by: ')) # value of the number to divide by
    except ValueError: # in case of a nonint input
        print('You should enter a valid number!')
        continue

    for a in range(x, y):
        try:
            if a % z == 0:
                 print(a, [a / z], end = ' ') 
        except ZeroDivisionError:
            print ("Cannot divide by zero")
            break

【讨论】:

    【解决方案2】:

    您可以尝试引发异常检查以下示例

    #!/usr/bin/env python3
    
    print('Find all numbers in range...')
    
    while True:
        try:
            x = int(input('From: ')) # begining of the range
            y = int(input('.. to: ')) # end of the range
            z = int(input('.. that can be divided by: ')) # value of the number to divide by
        except ValueError: # in case of a nonint input
            print('You should enter a valid number!')
            continue
    
        for a in range(x, y):
            try:
                if a % z == 0:
                    print(a, [a / z]) 
            except ZeroDivisionError as err: # issue with implementing this exception
                raise Exception("Cannot divide by zero", err)
    

    【讨论】:

    • 如果你想用异常解决它为什么不简单地让ZeroDivisionError传播?
    • 对不起,我想我忘了提到我的第一语言不是英语。传播是什么意思?
    • @Varad 感谢您的建议,我运行了您的示例并终止了程序,这不是我的目标。
    • @MichalFoc 我认为你不应该raise Exception。对不起,我弄错了你的问题。如果是这种情况,您可以给出print 语句,然后使用break 退出for 循环到while
    【解决方案3】:

    你怎么称呼回答你自己的问题?所以我尝试了一件我之前没有通过的事情,而不是通过我使用了 break 语句和 vuala。接下来我将尝试让它将结果写入一个简单的 .txt 文件,这是目前为止任何感兴趣的人的代码

    # Program that let's you find all numbers in any range defined by user
    # that can be divided without any reminder by the number also defined by user
    
    print('Find all numbers in range...')
    
    while True:
        try:
            x = int(input('From: ')) # begining of the range
            y = int(input('.. to: ')) # end of the range
            z = int(input('.. that can be divided by: ')) # value of the number to divide by
        except ValueError: # in case of a nonint input
            print('You should enter a valid number!')
            continue
    
        for a in range(x, y):
            try:
                if a % z == 0:
                    print(a, [a / z], end = ' ')
            except ZeroDivisionError: # in case of variable z = 0
                print('You shoudln\'t divide by 0!!')
                break
        break
    

    【讨论】:

    • 如果您希望程序在除以零事件时终止,最好按照@Varad 的建议引发异常
    • 不是这样,我想继续循环,直到用户输入正确的值
    • 明白了。我的回答提供了您正在寻找的功能。
    【解决方案4】:

    您可以在进入循环之前验证用户输入的除数。那么你就不需要在 for 循环中检查除以零错误了:

    while True:
        try:
            x = int(input('From: '))
            y = int(input('.. to: '))
    
            z = int(input('.. that can be divided by: '))
            if z == 0:
                print('You can\'t divide by 0!!')
                continue            
    
        except ValueError: # in case of a nonint input
            print('You should enter a valid number!')
            continue
    
        for a in range(x, y):
            if a % z == 0:
                print(a, [a / z], end = ' ')
        print()
    

    【讨论】:

      【解决方案5】:

      在您的代码中,可以捕获ZeroDivisionError 的唯一方法是变量z 的内容是否为0。此时,我注意到您的代码中存在一些问题:

      1. 在将 x 和 y 传递给 range() 函数之前,您应该确保 x < y
      2. 您应该始终确保z 不为空,然后脚本将检查它是否可以按照您想要的方式进行划分。

      这是我的建议:

      # Program that let's you find all numbers in any range defined by user
      # that can be divided without any reminder by the number also defined by user
      
      print('Find all numbers in range...')
      
      while True:
          try:
              x = int(input('From: ')) # begining of the range
              y = int(input('.. to: ')) # end of the range
              z = int(input('.. that can be divided by: ')) # value of the number to divide by
          except ValueError: # in case of a nonint input
              print('You should enter a valid number!')
              continue
          numbers = range(x, y)
          if len(numbers) > 0 and z != 0:  #Check if the list is empty and if the divider is not null
              for number in numbers:
                  if number % z == 0:
                      print(number, [number / z])
          else:
              print("Invalid numbers passed")`
      

      【讨论】:

      • 谢谢 Vinny,我喜欢你的想法,第 1 点肯定会被实现,因为我用 x > y 测试它给了我 0 个结果(尽管程序以代码 0 终止.. .),但是我认为有一点教育意义很好,您可以在其中温和地通知/提醒用户您不应该除以 0 :) 至于检查列表是否为空,我认为它已处理除了 ValueError。感谢您的意见
      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多