在 python 中实施 ZeroDivisionError 异常

Implementing ZeroDivisionError exception in python

所以,在编程方面我完全是菜鸟,只是在周末才开始学习 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) 次。有什么建议么?非常感谢

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

#!/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)

问题是您 try/except 在 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

你怎么叫回答你自己的问题?所以我尝试了一件我之前没有做过的事情,而不是通过我使用 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

您可以在进入循环之前验证用户输入的除数。那么你不需要在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()

在您的代码中,捕获 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")`