如果参数不是数字,如何重新启动函数?

 收藏

我正在写一个GPA计算器,我想确保输入的类数是一个数值。如果没有,如何使下面的函数返回?

def get_num_classes(n):
    num_classes = n
    if n.isnumeric():
        return int(num_classes)
    else:
        #???

In the main file, the function is called as: num_classes = grade_fcns.get_num_classes(input("Number of classes this semester: "))

回复
  • 别猜我心思 回复

    Considering that None does not make sense (I mean, this has no other sense as "Not a valid stuff"), I would try this:

    def get_num_classes(n):
        num_classes = n
        if n.isnumeric():
            return int(num_classes)
        return None #There's no need of else here, once we're talking about return statements
    
    

    and then call it from a while(True) statement:

    while (True):
        answer = get_num_classes(input("Number of classes this semester: "))
        if answer is not None:
            #Do something else
            break
        else:
            print("Try again...\n")
    

    This approach is not recursive, but you should be careful about the while(True), once it can hang there forever. You could even use a try/except approach, where you can, for instance, check for other criteria: is it an integer? Is it greater than 0? Is is between x and y? And, if these criteria are not met, raise an exception, like AttributeError and then catch it in the main code.

    希望能帮助到你

  • liste 回复

    Using a while loop to delegate the verification of the input to int:

    def get_num_classes():
        while True:
            try:
                return int(input("Number of classes this semester: "))
            except ValueError:
                print('Try again')
    
    print(get_num_classes())
    

    例:

    Number of classes this semester: s
    Try again
    Number of classes this semester: sd
    Try again
    Number of classes this semester: 3
    3
    

    该解决方案不倾向于无限递归(以及不可避免的堆栈溢出)。