How to limit the numbers to count

Question:

How to limit the numbers to count? I want average only grades 1-5. If user gives 0 or 6 then program does not count those numbers.

grade = 0
count = 0
total = 0

while grade > -1 :
    grade = int(input("Give a course grade (-1 exits): "))
    if grade == -1:
        break
    if grade == 0:
        print("Grades must be between 1 and 5 (-1 exits)")
    if grade >= 6:
       print("Grades must be between 1 and 5 (-1 exits)")
else:
    pass

# Add the grade to the running total
total = total + grade
count = count + 1

# Print the results.
if count > 0 :
    average = total / count

print("Average of course grades is:",round(average,1))
Asked By: Kia K

||

Answers:

Add this condition:

if grade >= 1 and grade <= 5:
   # whatever you want goes here
else:
   print("Please enter a valid value")
Answered By: Chandler Bong

Simply rearrange your logic flow:

  1. put all calculation in while loop and print result in else clause (when inp == -1)

  2. if inp is valid, do calculation, else prompt error message


grade = 0
count = 0
total = 0

while grade != -1 :
    grade = int(input("Give a course grade (-1 exits): "))
    if grade > 0 and grade <6:
        # Add the grade to the running total
        total = total + grade
        count = count + 1
    else:
        print("Grades must be between 1 and 5 (-1 exits)")

else:
    # Print the results.
    if count > 0 :
        average = total / count
        print("Average of course grades is:",round(average,1))
Answered By: ytung-dev

You can simplify this greatly by not keeping a running total and count but by building a list.

Your while loop can be controlled effectively with the walrus operator.

The range check can be dealt with easily using the comparison style shown in this example:

values = []

while (value := int(input('Enter a grade between 1 and 5 or -1 to exit: '))) != -1:
    if 1 <= value <= 5:
        values.append(value)
    else:
        print('Invalid grade')

if values:
    print(f'Average = {sum(values)/len(values)}')
else:
    print("Oops! You didn't enter any values")

Note:

Any values entered that cannot be converted to int will cause a ValueError exception. You should consider enhancing your code to allow for this eventuality

Answered By: OldBill
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.