[英]Zero division error in python function even after using if-statement to avoid division by 0
我正在編寫一個 function ,它返回可以划分 integer 的總位數(整數)。 對於前 Integer -111 計數 - 3 作為所有 1,1,1 除 111 Integer - 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)
即使divisor != 0
, int(divisor)
也可以為0
。
>>> divisor = 0.5
>>> int(divisor)
0
我建議請求寬恕而不是許可,然后抓住ZeroDivisionError
。
try:
if n%int(divisor) == 0:
count += 1
except ZeroDivisionError:
pass
問題是將字符串用作整數的錯誤使用。
修復代碼的一種方法是:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.