1

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)
1
  • 1
    What is this supposed to do? What happens to score, why do you add the loopcounter to the score, and why do you never update oldCcore? Commented Feb 21, 2014 at 17:57

4 Answers 4

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

You want to keep asking the user a new input while its a greater number each time. You can use a list to keep every score entered and then use the sum built-in function to do the work for you:

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

1 Comment

you can drop your loopCounter variable if you do len(scores)+1 instead.
1

Your code has various issues and won't even run. Here's a working version that does approximately what you seem to want.

Managing old and new values using a while loop is a common idiom in coding and worth practicing.

EDIT: I buggered up the order of the lines of code myself. The code now gives the correct averages.

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)

Comments

1

Following Raymond Hettinger's talk and Amir's blog post http://blog.amir.rachum.com/blog/2013/11/10/python-tips-iterate-with-a-sentinel-value/

In [1]: def loop():
   ...:     old = 0
   ...:     while True:
   ...:         new = raw_input("gimme")
   ...:         yield new > old
   ...:         old = new
   ...:         

In [2]: l = loop()

In [4]: list(iter(l.next, False))
gimme1
gimme2
gimme0
Out[4]: [True, True]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.