Python:为什么我在函数中得到“zero division error:division by zero”?
回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我的目标是统计一个文件中属于特定时区的tweet总数。
我有以下功能(我注意到功能末尾附近的故障区域并给出了注释):</p>
<pre><code>def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0
for line in inFile:
entry = line.split()
for n in range(0, len(entry) - 1):
entry[n] = entry[n].strip("[],!?#./-=+_@")
if n > 4: # n>4 because words begin on 5th index of list
entry[n] = entry[n].lower()
words.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(entry[n])
lat = float(entry[0])
long = float(entry[1])
timezone = getTimeZone(lat, long)
if timezone == "eastern":
easternTweets += 1
if timezone == "central":
centralTweets += 1
if timezone == "mountain":
mountainTweets += 1
if timezone == "pacific":
pacificTweets += 1
for i in range(0, len(words)):
for k in range(0, len(keyword)):
if words[i] == keyword[k]:
value = int(sents[k])
if timezone == "eastern":
eastern += value
a += 1
if timezone == "central":
central += value
b += 1
if timezone == "mountain":
mountain += value
c += 1
if timezone == "pacific":
pacific += value
d += 1
# the values of a,b,c,d are 0
easternTotal = eastern/a # getting error
centralTotal = central/b # for
mountainTotal = mountain/c # these
pacificTotal = pacific/d # values
print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)
</code></pre>
<p>我得到了一个<code>ZeroDivisionError: division by zero</code>错误,<code>easternTotal</code>和其他使用<code>a</code>、<code>b</code>、<code>c</code>和{<cd6>}进行除法的总值。在</p>
<p>如果我打印<code>a</code>、<code>b</code>、<code>c</code>、或{<cd6>}的值,则显示<code>0</code>。我的问题是为什么它们的值是0?<code>a</code>、<code>b</code>、<code>c</code>、和{<cd6>}的值在<code>if</code>语句中没有变化吗?在</p>