[英]How to fix ZeroDivisionError: Division by zero?
運行代碼后,我收到一個 ZeroDivisionError! 有人可以解釋發生了什么嗎? 尋找 bscore 和 gscore 輸入的平均值
bscore = 0
gscore = 0
bcount = 0
gcount = 0
choice = input("Boy (b), Girl (g) or Quit (q): ")
while (choice != 'q'):
if(choice == 'b'):
score = int(input("Boy score: "))
bscore += score
bcount == 1
#z = (x / y) if y != 0 else 0
elif(choice =='g'):
score = int(input("Girl score: "))
gscore += score
gcount += 1
else:
print("Invalid!")
choice = input("Boy (b), Girl (g) or Quit (q): ")
print("Boy average is: ", (bscore/bcount))
print("Girl average is: ", (gscore/gcount))
您需要用bcount += 1
替換bcount == 1
bcount += 1
。 bcount == 1
是一個布爾語句,在這里不做任何事情。 看起來你想在那個時候增加計數。
此外,即使在那之后,也可能存在ZeroDivisionError
因為輸入可能永遠不是b
或g
。 我建議在打印時嘗試分割之前有一個 if 條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.