返回for循环中的特定数字

时间:2018-11-30 18:45:59

标签: python python-3.x

我有以下代码:

def five_numbers():
    my_list = []
    for i in range(1, 6):
        user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
        my_list.append(user_nr)
    return my_list

def check_if_number_is_1_to_25(number):
    if number.isalpha():
        print("Enter a number between 1 and 25.")
        # Here I want to go back to five_numbers() and the number x (for example number 4)

现在,我要检查输入内容是否包含任何字母。如果有的话,我想打印一条消息,然后再返回到用户先前使用的电话号码。我试图返回Five_numbers(),但是用户将从头开始。

感谢所有帮助。

3 个答案:

答案 0 :(得分:1)

为num添加关键字arg,并将其默认设置为None

def five_numbers(num=None):
    my_list = []
    if num is None:
        for i in range(1, 6):
            user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
            my_list.append(user_nr)
    else:
        # do other stuff with num (4) here...
    return my_list

def check_if_number_is_1_to_25(number):
    if number.isalpha():
        print("Enter a number between 1 and 25.")
        five_numbers(4)

答案 1 :(得分:0)

您可以使用while循环不断询问用户有效的输入,直到用户输入一个为止。您还应该使check函数引发一个异常,以便调用者可以捕获该异常并重试输入:

def five_numbers():
    my_list = []
    for i in range(1, 6):
        while True:
            user_nr = input("Number " + str(i) + ": ")
            try:
                check_if_number_is_1_to_25(user_nr)
                break
            except ValueError as e:
                print(str(e))
        my_list.append(user_nr)
    return my_list

def check_if_number_is_1_to_25(number):
    if number.isalpha():
        raise ValueError('Enter a number between 1 and 25.')

答案 2 :(得分:0)

不要使用for循环,请使用while循环以列表长度为条件。使 check 函数返回一个布尔值,并使用它来决定是否将其追加到列表中。

def five_numbers():
    my_list = []
    while len(my_list) < 5:
        user_nr = input("Number {}: ".format(len(my_list)+1))
        if check_if_number_is_1_to_25(user_nr):
            my_list.append(user_nr)
        else:
            print("Enter a number between 1 and 25.")
    return my_list

def check_if_number_is_1_to_25(number):
    return number.isdigit() and (1 <= float(number) <= 25)