Reputation: 39
Im trying to write a program that will determine the average of a number tests. The number of tests will vary, but I do not want it to be initially set by user input. I'm want to use a while loop and a sentinel value of zero to stop the input. I would like the average to display to three decimal places, with the % symbol immediately following the final digit as shown below... SAMPLE RUN: Enter test score 80 Enter test score 70 Enter test score 90 Enter test score 88 Enter test score 0 The average is 82.000%
total =0
counter = 0
while True:
entry = int(input('Enter test score:'))
if entry ==0:
break
total += entry
counter += 1
average = (total/counter)
print("The average score:",format(average, '.3f'),'%',sep='')
Upvotes: 0
Views: 9297
Reputation: 39
total =0
counter = 0
while True:
entry = int(input('Enter test score:'))
if entry ==0:
break
total += entry
counter += 1
average = (total/counter)
print("The average score:",format(average, '.3f'),'%',sep='')
Upvotes: 0
Reputation: 1531
total = 0
counter = 0
while True:
entry = int(input("Enter Test score: "))
if entry == 0: break
total += entry # this should be in while loop
counter += 1
total = total * 1.0
if counter == 0: exit(1)
avg = total / counter
print("Average is: %3.f" % avg + '%')
total += entry should be inside while loop, because you want to add it for every entry received. hope that helped :)
Upvotes: 0
Reputation: 3551
The following should work.
scores = []
while True:
entry = input("Enter test score: ")
if entry == '':
break
elif not entry.isnumeric():
print("Scores must be numeric.")
else:
scores.append(int(entry))
average = sum(scores)/len(scores)
print("The average score is {:.03f}.".format(average))
The average is computed by taking the sum of the list of scores
and dividing it by the total number of elements in scores
. The rest is just logic to ensure that the user inputs numeric scores and exit when the user enters nothing (just presses Return with no text).
Upvotes: 0
Reputation: 16147
It doesn't look like you even tried, because your code as is in not able to run at all. However, here is the answer. You'll want to store the results in a list, then get the average by the sum of the list over the length of the list (number of scores). the .format method allows you to specify 3 decimal places.
scores = []
while True:
entry = int(input('Enter test score: '))
if entry == 0:
break
scores.append(entry)
print('The average is', "{0:.3f}".format(float(sum(scores) / len(scores))))
Upvotes: 0
Reputation: 36033
While
needs to be all lowercase.
if entry == 0
is missing a colon.
total += entry
and counter += 1
need to be inside the loop since they must happen with every iteration.
Did you try running the code you had before posting here?
Upvotes: 1