如何创建需要用户输入的子程序?

时间:2019-10-18 11:14:00

标签: python user-input

我有重复的(有效的)代码,用于使用户选择某些选项。遵循DRY原理,我试图通过创建一个子函数来压缩此重复的代码,该子函数将一些参数传递给子函数并获得有效的用户输入

我尝试了以下方法: 然后我从主程序中调用该方法,并传递列表和描述字符串


def get_user_input(choice_list,data_name):
    """
    Used to get data from the user to analyze.

    Returns:
        (str)
    """
    input_num = 0

    while True:
        # print out the options
        for i in range(len(choice_list)):
            print(str(i+1)+":", choice_list[i])
        # try to get the user to select an option
        try:
            input_num = int(input("Enter the number that represents the {0}}:".format(data_name)))
            if input_num in range(1, len(choice_list)+1):
                return_value = choice_list[input_num-1]
                print('Great, you have choosen the {0}: '.format(data_name) + choice_list + '\n')
                return return_value
                #break
            else:
                print("invalid choice, please try again")
        except ValueError:
            print('Thats not a valid number please try again')
            continue


# call from main program:

# Get user input for city (chicago, new york city, washington).
cities = ['Chicago', 'New York city', 'Washington']

city = get_user_input(cities,"city")

这是我的工作代码,使用略有不同的参数重复3次以从用户获得不同的输入:

    while True:
        # print out city options
        for i in range(len(cities)):
            print(str(i+1)+":", cities[i])

        # get user to select a city
        try:
            citynum = int(input("Enter the number that represents the city:"))
            if citynum in range(1, len(cities)+1):
                city = cities[citynum-1]
                print('Great, you have choosen the city: ' + city + '\n')
                break
            else:
                print("invalid choice, please try again")
        except ValueError:
            print('Thats not a valid number please try again')
            continue

            if debug_flag:
                print('debug citynum= {0}'.format(citynum))

问题是,当我调用此“紧凑”功能时,它只是一遍又一遍地重复(陷入循环) 我希望能够调用此子程序,传递信息并从用户输入中获取结果。

2 个答案:

答案 0 :(得分:0)

格式字符串有问题

input_num = int(input("Enter the number that represents the {0}}:".format(data_name)))
#                                            here extra brace  ^ 

答案 1 :(得分:0)

您还有一个额外的“}”,这引发了input_num = int(input("Enter the number that represents the {0}}:".format(data_name)))

中的值错误

这就是为什么它陷入无限循环的原因。