验证输入的更好方法?

2024-06-07 19:43:50 发布

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

我有一段代码,从用户输入中提取5个等级,检查等级是0到100,还是输入是非数字值,并一直尝试,直到您给出有效的输入。你知道吗

def main(x):
    counter = 0
    grade = x
    grades = [0] * 5
    incount = ["first", "second", "third", "fourth", "fifth"]
    average = 0
    restart = ""

    # try 5 times to validate input and set the 5 grades if valid
    while counter < 4:
        try:
            grade = int(grade)
            if grade > 100 or grade < 0:
                print("Please enter a number from 0 to 100!")
            else:
                grades[counter] = grade
                counter = counter + 1
        except:
            print("Please enter a valid numerical value.")
        grade = input("Enter the " + incount[counter] + " grade. ")
    grades[counter] = grade

如果这个问题没有得到验证,那就是五年级的问题了。我能做些什么来确保第五个模块已经验证并且可以开始使用这个模块

def start():
    grade = 0
    print("To get a grade average, please enter five grades one by one from 
    0 to 100.")
    grade = input("Enter the first grade. ")
    main(grade)

编辑:

    while counter < 5:
        try:
            grade = int(grade)
            if grade > 100 or grade < 0:
                print("Please enter a number from 0 to 100!")
            else:
                grades[counter] = grade
                counter = counter + 1
        except:
            print("Please enter a valid numerical value.")
        if counter < 5:
            grade = input("Enter the " + incount[counter] + " grade. ")
    grades[counter - 1] = grade

我接受了循环额外时间的建议,但我不想添加决策语句来避免上一个循环的另一个输入。对于上一个循环来说,这似乎是一个廉价的修复,但是我不知道如何在不接受其他输入的情况下验证所有5个值。你知道吗


Tags: thetofrominputifcountergradegrades
2条回答

我已经偏离了您首选的解决方案方向,决定使用一个自调用函数来检查调用计数器和长度

对于数字<;0或>;100,还有一个自定义异常,它被引发并捕获以提供所需的用户流。你知道吗

# coding: utf-8
class InvalidIntError(Exception):
    ''' our custom exception '''
    pass


def average_grade(grades_marks, grade_title, counter):
    grades = ['first', 'second', 'third', 'fourth', 'fifth']

    # for the first loop use the original grades list
    if counter > 0:
        # for subsequent calls to this function always start looping grades from passed grade_title
        current_index = grades.index(grade_title)
        new_grades = grades[current_index:]
        print(
            f'The current index {current_index} , the current grades {new_grades}'
        )
        grades = new_grades

    try:
        print(f'Counter {counter}, using grades :> {grades}')

        for grade_title in grades:
            grade = int(input(f'Enter the {grade_title} grade :> '))
            if grade > 100 or grade <= 0:
                raise InvalidIntError(
                    f'Your grade is < 0 or > 100.Enter the {grade_title} grade :> '
                )
            grade = int(grade)
            grades_marks.append(grade)
            print(grades_marks)
            counter += 1
        print('Gotten grade values calculating the average')
        average = sum(grades_marks) / len(grades_marks)
        print(f'grades given as {grades_marks},\n the average is :> {average}')
    except ValueError as e:
        # means we have given a non integer, so rerun function
        print('error ', e)
        average_grade(grades_marks, grade_title, counter)
    except InvalidIntError as e:
        # an int < 0 or > 100
        print('error ', e)
        average_grade(grades_marks, grade_title, counter)


if __name__ == '__main__':
    grades_marks = []
    average_grade(grades_marks, 'first', 0)

样品运行

$ python infinite_validation.py
Counter 0, using grades :> ['first', 'second', 'third', 'fourth', 'fifth']
Enter the first grade :> 20
[20]
Enter the second grade :> f
error  invalid literal for int() with base 10: 'f'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> g
error  invalid literal for int() with base 10: 'g'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> f
error  invalid literal for int() with base 10: 'f'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> 20
[20, 20]
Enter the third grade :> 40
[20, 20, 40]
Enter the fourth grade :> 12
[20, 20, 40, 12]
Enter the fifth grade :> 9000000000000221211
error  Your grade is < 0 or > 100.Enter the fifth grade :>
The current index 4 , the current grades ['fifth']
Counter 4, using grades :> ['fifth']
Enter the fifth grade :> 40
[20, 20, 40, 12, 40]
Gotten grade values calculating the average
grades given as [20, 20, 40, 12, 40],
 the average is :> 26.4

注意:您可以删除一些多余的print debug语句。你知道吗

您在while循环中只迭代了4次,因为您的条件是严格的劣势。你知道吗

counter只接受以下值:0、1、2、3、4。但是对于4,它不向条件输出TRUE

您应该将最大值从4更改为5或将运算符从<更改为<=

相关问题 更多 >

    热门问题