无论压痕如何,都不会打印计数或平均值

时间:2017-11-03 00:54:10

标签: python-3.x

我必须制作一个程序,允许用户输入成绩,直到他们输入负数,然后输出通过成绩和失败成绩的平均值。我们不允许使用列表功能。

maxgrade = 100
mingrade = 0
passing = 0
failing = 0


while True:
    try:
        grade = int(input("Enter a grade: "))

        if 100 >= grade > 60:
            passing += 1
        elif grade <= 60:
            failing += 1
        if grade < 0:
            print("Invalid")


        if grade < mingrade:
            mingrade = grade
        if grade > maxgrade:
            maxgrade = grade

        total == grade
        count = passing + failing
        avg = total/count

        print("Average: ", avg)
        print("# Passing: ", passing)
        print("# Failing: ", failing)

    except:
             print("Invalid")
             break

1 个答案:

答案 0 :(得分:0)

首先,正如我在评论中提到的,您对tryexcept的使用不正确。 Tryexcept串联使用以防止错误发生。但是,在您的情况下,我怀疑甚至需要tryexcept。请参阅以下代码了解解决方法。

您还需要考虑您的逻辑和代码执行顺序。以下带注释的代码将按指定的方式工作。

# Assume the lowest and highest possible for max and min grades, respectively
max_grade = 0
min_grade = 100
grade_sum = 0
passing_count = 0
failing_count = 0

# Loop sentinel
running = 1

# Main loop
while running:

    # Input validation sentinel
    invalid_input = 1

    # Input validation loop
    while invalid_input:
        grade = input("Enter a grade: ")
        if grade.isnumeric():
            grade = int(grade)
            invalid_input = 0
        else:
            print("Please enter a number!")

    # Increment number of passing or failing grades
    if 100 >= grade > 60:
        passing_count += 1
    elif 60 >= grade >= 0:
        failing_count += 1
    else:
        running = 0

    # Update grade_sum
    grade_sum += grade        

    # Update min_grade and max_grade
    if grade < min_grade:
        min_grade = grade
    if grade > max_grade:
        max_grade = grade

# Calculate grade average
grade_avg = grade_sum / (passing_count + failing_count)

# Print results
print("Average: ", grade_avg)
print("# Passing: ", passing_count)
print("# Failing: ", failing_count)