我正在编写一个函数,该函数返回(整数)位数的总计数,该总数可以除以它所属于的整数。对于前整数-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)
问题是将字符串作为整数使用不正确。
修复代码的一种方法是:
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
[int(divisor)
可以是0
,即使divisor != 0
。
>>> divisor = 0.5
>>> int(divisor)
0
我建议征求宽恕而不是允许,只是抓住ZeroDivisionError
。
try:
if n%int(divisor) == 0:
count += 1
except ZeroDivisionError:
pass