即使使用if语句避免被0除,Python函数中的零除法错误

问题描述 投票:0回答:2

我正在编写一个函数,该函数返回(整数)位数的总计数,该总数可以除以它所属于的整数。对于前整数-111 数-3作为所有1,1,1除数111 整数-103456 数-2仅可被1,4整除。为了处理除以0的特殊情况,我使用了if-else语句。但是,我仍然遇到零除法错误。为什么我仍然收到此错误?我的错误消息:-ZeroDivisionError:integer division or modulo by zero

我的代码-

    count=0
    divisors_list=[]
    number_in_string = str(n)
    divisors_list=list(number_in_string)
    for divisor in divisors_list:
       if divisor != 0:
            if n%int(divisor) == 0:
               count+=1
    return count

x=findDigits(103456)
python python-3.x function divide-by-zero
2个回答
1
投票

问题是将字符串作为整数使用不正确。

修复代码的一种方法是:

def findDigits(n):
    count = 0
    number_in_string = str(n)
    divisors_list = list(number_in_string)
    for divisor in divisors_list:
        # *** at this point, divisor is a string ***
        divisor = int(divisor)  # <== cast it to int
        if divisor != 0:
            if n % divisor == 0:
               count += 1
    return count

1
投票

[int(divisor)可以是0,即使divisor != 0

>>> divisor = 0.5
>>> int(divisor)
0

我建议征求宽恕而不是允许,只是抓住ZeroDivisionError

try:
    if n%int(divisor) == 0:
        count += 1
except ZeroDivisionError:
    pass
© www.soinside.com 2019 - 2024. All rights reserved.