簡體   English   中英

如何創建一個接受用戶輸入的子程序?

[英]how to create a sub program that takes user input?

我重復了(工作)代碼,用於讓用戶使用 select 一些選項。 遵循 DRY 原則,我試圖通過創建一個子 function 來壓縮這個重復的代碼,我將一些參數傳遞給它並獲取有效的用戶輸入

我嘗試了以下方法:然后我從我的主程序中調用它,傳遞列表和字符串以進行描述


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))

問題是,當我稱之為“緊湊”function 時,它只是一遍又一遍地重復自己(陷入循環)我希望能夠調用這個子程序,傳遞信息並從用戶輸入中獲取結果。

您的格式字符串有問題

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

您有一個額外的“}”,它會在input_num = int(input("Enter the number that represents the {0}}:".format(data_name)))中引發值錯誤

這就是為什么它陷入無限循環的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM