Sentinel Loop Python

user3254943 picture user3254943 · Feb 21, 2014 · Viewed 8.3k times · Source

How should I set up a sentinel loop in python where the loop keeps running only if the new inputed number is greater than the old inputed number?

This is what I have right now, but I know it's not right.

    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)

Answer

Adam Smith picture Adam Smith · Feb 21, 2014

The de facto way of handling this is to use a list rather than throwing away the individual scores each time.

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))