Skip to content Skip to sidebar Skip to footer

How To Average User Inputs With While Loop Using A Sentinal Value?

For a classroom assignment I have been asked to create a program that averages a number of user input exam grades using a while loop. I have come up with a functioning program, how

Solution 1:

Think the best way to do it would be store the scores in a list and then compute the average of them after the user enters the sentinel value:

SENTINEL = float(9999)

scores = []
whileTrue:
    number = float(input("Enter exam score (9999 to quit): "))
    if number == SENTINEL:
        break
    scores.append(number)

ifnot scores:
    print("You didn't enter any scores.")
else:
    avg = sum(scores)/len(scores)
    print("average of ", len(scores), " test scores is :", avg)

Solution 2:

There are a couple ways to go about this. The general approach would be to keep a running total of the scores, as well as how many scores you've read, and then check whether the next score to read is == 9999 to see whether or not to exit the while loop.

A quick version might be the following:

num_scores = 0
total_sum = 0
shouldExit = Falsewhile shouldExit isFalse:
    nextScore = float(input("Enter exam score : "))
    if nextScore == 9999: #find a way to do this that does not involve a == comparison on a floating-point number, if you can
        shouldExit = Trueif shouldExit isFalse:
        num_scores += 1
        total_sum  += nextScore
avg = total_sum / num_scores

See how that sort of approach works for you

Solution 3:

You can just break out of your for loop after getting input.

for n in range(scores):
    c = int(Input('Enter test score, enter 9999 to break'))
    ifc== 9999:
       break;
    scores += c

Something like that at least.

Post a Comment for "How To Average User Inputs With While Loop Using A Sentinal Value?"