简体   繁体   中英

how to create a sub program that takes user input?

I have repeated (working) code that is used to get the user to select some options. Following the DRY principle i am trying to compact this repeated code by creating a sub function that i pass some parameters to and get the valid user input

I have tried the following: which i then call from my main program passing over the list and string for the description


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

This is my working code, that is repeated 3 times with slightly different parameters to get different input from the user:

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

The issue is, when i call this 'compact' function it just repeats itself over and over (stuck in a loop) Id like to be able to call this sub program, passing the information and getting the results from the user input.

You have a problem in your formatting string

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

You have an extra "}" that is raising the value error in input_num = int(input("Enter the number that represents the {0}}:".format(data_name)))

That is why it's stuck in an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM