我该如何做,以便用户只有两次尝试输入有效的输入?

时间:2018-09-29 14:50:17

标签: python loops reset

print('Hello, welcome to your grade calculator.')
GradeCount = 0
totalGrades = 0.0
moreStudent = 'y'

while moreStudent == 'y' or moreStudent == 'Y':
    grade = float(input('Enter a grade or a -1 to end: '))
    while grade != -1:
        if grade > 100 or grade < 0:
            print('Invalid input. Please enter a value between 1 and 100.')
            grade = float(input('Enter the next grade or -1 to end: '))
            continue
        totalGrades = totalGrades + grade
        GradeCount = GradeCount + 1
        if 90 <= grade <=100:
            print('You got an A. Thats awesome.')
            print('Number of grades entered: ',GradeCount)
            print('Class total: ',totalGrades)
        elif 80 <= grade < 90:
            print('You got a B. Good job.')
            print('Number of grades entered: ',GradeCount)
            print('Class total: ',totalGrades)
        elif 70 <= grade < 80:
            print('You got a C. Thats fine I guess.')
            print('Number of grades entered: ',GradeCount)
            print('Class total: ',totalGrades)
        elif 60 <= grade < 70:
            print ('You got a D. Not very good.')
            print('Number of grades entered: ',GradeCount)
            print('Class total: ',totalGrades)
        elif grade < 60:
            print ('You got an F. You fail.')
            print('Number of grades entered: ',GradeCount)
            print('Class total: ',totalGrades)
        grade = float(input('Enter the next grade or -1 to end: '))
    moreStudent = input('Are you a new student and ready to enter your 
grades? y or n: ')
print ('Number of grades entered:', GradeCount)
print ('Class total:',totalGrades)
print ('Class grade average:', format(totalGrades / GradeCount, '.2f'))

我如何做到这一点,使用户在程序发出错误消息之前只有2次尝试,然后清除屏幕并重新开始?另外,每次有新用户时,如何使屏幕清晰?

1 个答案:

答案 0 :(得分:0)

您可以对当前代码进行的最基本的修改是添加一个计数器,也可以使用其他方法

while moreStudent == 'y' or moreStudent == 'Y':
    grade = float(input('Enter a grade or a -1 to end: '))
    count = 0
    while grade != -1:
        if grade > 100 or grade < 0:
            count += 1
            if count == 2:
                moreStudnet = 'n'
                break
            else:
                print('Invalid input. Please enter a value between 1 and 100.')
                grade = float(input('Enter the next grade or -1 to end: '))
                continue
        totalGrades = totalGrades + grade
        GradeCount = GradeCount + 1