【问题标题】:How can I make it so the user only has 2 tries to enter valid input?我怎样才能使用户只有 2 次尝试输入有效输入?
【发布时间】:2018-09-29 14:50:17
【问题描述】:
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 次尝试,然后清除屏幕并重新开始?另外,每次有新用户时如何清除屏幕?

【问题讨论】:

  • 这是什么语言?请酌情标记。
  • 为什么不使用像tries += 1这样的计数器变量?

标签: python loops reset


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2015-02-07
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多