簡體   English   中英

我該如何做,以便用戶只有兩次嘗試輸入有效的輸入?

[英]How can I make it so the user only has 2 tries to enter valid input?

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

我該如何做,以便用戶在程序發出錯誤消息之前只有兩次嘗試,然后清除屏幕並重新開始? 另外,每當有新用戶時,如何使屏幕清晰?

您可以對當前代碼使用的最基本的修改是添加一個計數器,也可以使用其他方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM