简体   繁体   中英

How to limit the numbers to count

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

Add this condition:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM