2014-03-12 37 views
1

當我測試一個計數器時,我發現它似乎只顯示最後一個項目通過它。例如,如果某件事情非常好,那麼它就會顯示爲「1」。然而,不管其他數據如何,其餘數據將爲0.計數器似乎並沒有正確添加

def mealrating(score, review): 
    for x in range(0,len(score)): 

     mp = 0 
     mg = 0 
     me = 0 
     if score[x] >= 1 and score[x] <= 3: 
      review.append("poor") 
      mp = mp + 1 

     if score[x] >= 4 and score[x] <= 6: 
      review.append("good") 
      mg = mg + 1 

     if score[x] >= 7 and score[x] <= 10: 
      review.append("excellent") 
      me = me + 1 

    print("The customer rated tonight's meal as:") 
    print('Poor:' + str(mp)) 
    print('Good:' + str(mg)) 
    print('Excellent:' + str(me)) 
    print("\n") 

回答

2

您將在每次迭代中重置mp,mg和me。

def mealrating(score, review): 
    mp = 0 
    mg = 0 
    me = 0 

    for x in range(0,len(score)): 
     if score[x] >= 1 and score[x] <= 3: 
      review.append("poor") 
      mp = mp + 1 

     if score[x] >= 4 and score[x] <= 6: 
      review.append("good") 
      mg = mg + 1 

     if score[x] >= 7 and score[x] <= 10: 
      review.append("excellent") 
      me = me + 1 

    print("The customer rated tonight's meal as:") 
    print('Poor:' + str(mp)) 
    print('Good:' + str(mg)) 
    print('Excellent:' + str(me)) 
    print("\n") 
1

您必須初始化櫃檯外循環:

mp = 0 
mg = 0 
me = 0 
for x in range(0, len(score)): 
    # same as before 

否則,他們會得到在每個迭代復位!爲了使你的代碼更Python,採取下面的提示考慮:

  • 形式x >= i and x <= j可以更簡潔爲i <= x <= j
  • 慣用的方法來遍歷一個列表使用迭代器,寫不明確使用的條件指標
  • 的條件是相互排斥的,所以你應該使用elif
  • 使用+=遞增變量

這就是我的意思:

mp = mg = me = 0 
for s in score: 
    if 1 <= s <= 3: 
     review.append("poor") 
     mp += 1 
    elif 4 <= s <= 6: 
     # and so on