如何使用户只需2次尝试输入有效输入?

2024-09-28 01:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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次尝试?还有,我怎样才能在每次有新用户时都清楚地显示屏幕


Tags: oroftoyounumberinputclasstotal
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:28

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

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

相关问题 更多 >

    热门问题