2014-02-21 28 views
-1

我應該如何在python中設置一個哨兵循環,只有當新輸入的數字大於舊的輸入數字時循環纔會繼續運行?Sentinel Loop Python

這就是我現在的情況,但我知道這是不對的。

totalScore = 0 
    loopCounter = 0 
    scoreCount = 0 
    newScore = 0 
    oldscore = newscore - 1 
    print("Enter the scores:") 
    score = (raw_input("Score 1")) 
    while newScore >= oldScore: 
     newScore = int(raw_input("Score ") + (loopCounter + 1)) 
     scoreTotal = scoreTotal+newScore+oldScore 
     scoreCount = scoreCount + 1 
     loopCounter = loopCounter + 1 
    averageScore = scoreTotal/scoreCount 
    print "The average score is " + str(averageScore) 
+1

這是什麼應該做的? 'score'會發生什麼,爲什麼你在評分中加入'loopcounter',爲什麼你不更新'oldCcore'? –

回答

1

處理這種情況的事實上的方法是使用一個列表,而不是扔掉每次個人得分。

scores = [0] # a dummy entry to make the numbers line up 
print("Enter the scores: ") 
while True: # We'll use an if to kick us out of the loop, so loop forever 
    score = int(raw_input("Score {}: ".format(len(scores))) 
    if score < scores[-1]: 
     print("Exiting loop...") 
     break 
     # kicks you out of the loop if score is smaller 
     # than scores[-1] (the last entry in scores) 
    scores.append(score) 
scores.pop(0) # removes the first (dummy) entry 
average_score = sum(scores)/len(scores) 
# sum() adds together an iterable like a list, so sum(scores) is all your scores 
# together. len() gives the length of an iterable, so average is easy to test! 
print("The average score is {}".format(average_score)) 
1

你想不斷要求用戶輸入一個新的數字,而每次輸入一個更大的數字。您可以使用一個列表,以保持每一個得分進入,然後使用sum built-in function做的工作適合你:

scores = [] 
while True: 
    current_size = len(scores) 
    score = int(raw_input("Score %s" % (current_size + 1))) 
    # Check if there's any score already entered and then if the new one is 
    # smaller than the previous one. If it's the case, we break the loop 
    if current_size > 0 and score < scores[-1]: 
     break 
    scores.append(score) 

# avg = total of each scores entered divided by the size of the list 
avg = sum(scores)/len(scores) 
print "The average score is %s" % avg 
+0

你可以放棄你的'loopCounter'變量,如果你這樣做'len(scores)+ 1'。 –

+0

@adsmith yep,done :) –

1

你的代碼中有各種問題,將不能運行。這是一個工作版本,可以完成你想要的功能。

使用while循環管理舊值和新值是編碼中常見的習慣用法,值得練習。

編輯:我搞砸了自己的代碼行的順序。現在的代碼給出了正確的平均值。

scoreTotal = 0 
loopCounter = 0 
scoreCount = 0 
newScore = 0 
oldScore = 0 
print("Enter the scores:") 
newScore = int(raw_input("Score 1: ")) 
while newScore >= oldScore: 
    scoreTotal += newScore 
    scoreCount += 1 
    loopCounter += 1 
    oldScore = newScore 
    newScore = int(raw_input("Score " + str(loopCounter + 2) + ": ")) 
averageScore = float(scoreTotal)/float(scoreCount) 
print scoreTotal, scoreCount 
print "The average score is " + str(averageScore)