【问题标题】:Zero division error in python function even after using if-statement to avoid division by 0即使在使用 if 语句避免除以 0 之后,python 函数中的除法为零错误
【发布时间】:2020-06-13 06:22:52
【问题描述】:

我正在编写一个函数,该函数返回(整数)的总位数,该数可以除它所属的整数。 对于前整数 -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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

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

      我建议请求宽恕而不是许可,然后抓住ZeroDivisionError

      try:
          if n%int(divisor) == 0:
              count += 1
      except ZeroDivisionError:
          pass
      

      【讨论】:

      • 或字符串:”0”.
      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多