Using user input to Select an Option from a List in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Using user input to select an option from a list in Python
  2. Multiple choice question with user Input in Python
  3. Using the inquirer package to select an option with user input

# Using user input to select an option from a list in Python

To use user input to select an option from a list:

  1. Construct a message that contains the options.
  2. Use the input() function to take user input.
  3. Check if the user entered one of the possible options.
main.py
options = ['python', 'js', 'ts'] user_input = '' input_message = "Pick an option:\n" for index, item in enumerate(options): input_message += f'{index+1}) {item}\n' input_message += 'Your choice: ' while user_input.lower() not in options: user_input = input(input_message) print('You picked: ' + user_input)

select option input from list

The code for this article is available on GitHub

The example lets the user select one of the options in the list.

The user is expected to type the word, e.g. python, js, ts, but you could also tweak this and have the user type a number that corresponds to a list item.
main.py
options = ['python', 'js', 'ts'] user_input = '' input_message = "Pick an option:\n" for index, item in enumerate(options): input_message += f'{index+1}) {item}\n' input_message += 'Your choice: ' while user_input not in map(str, range(1, len(options) + 1)): user_input = input(input_message) print('You picked: ' + options[int(user_input) - 1])

select option input from list using integers

The code snippet above expects the user to enter a number that corresponds to the list item.

We used a formatted string literal to construct the input message.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # ๐Ÿ‘‰๏ธ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second is the item.

main.py
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # ๐Ÿ‘‰๏ธ 0 apple, 1 banana, 2 melon

On each iteration, we add 1 to the index to have the options start at 1.

main.py
options = ['python', 'js', 'ts'] user_input = '' input_message = "Pick an option:\n" for index, item in enumerate(options): input_message += f'{index+1}) {item}\n' input_message += 'Your choice: ' while user_input not in map(str, range(1, len(options) + 1)): user_input = input(input_message) print('You picked: ' + options[int(user_input) - 1])
The code for this article is available on GitHub
We used a while loop to keep iterating until the selected option is one of the values in the list or one of the corresponding numbers.

Once the user picks a valid option, the condition is no longer met and we exit out of the while loop.

Here is another example.

# Multiple choice question with user Input in Python

To define a multiple-choice question with user input:

  1. Use the input() function to take input from the user.
  2. Check if the input is one of the specified choices.
  3. Use conditional statements to check if the input is one of the available choices.
main.py
user_input = '' while True: user_input = input( 'Pick one: 1) Python | 2) JavaScript | 3) TypeScript [1/2/3]? ') if user_input == '1': print('You picked Python') break elif user_input == '2': print('You picked JavaScript') break elif user_input == '3': print('You picked TypeScript') break else: print('Type a number 1-3') continue

python user input multiple choice

The code for this article is available on GitHub

We used a while True loop to iterate until the user types in one of the options.

The only way to break out of a while True loop is to use the break statement.

The break statement breaks out of the innermost enclosing for or while loop.

The continue statement continues with the next iteration of the loop.

The continue statement is used to prompt the user again if they enter an incorrect option.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

Note that the input() function is always guaranteed to return a string, even if the user enters a number.

You can also use letters for the options.

main.py
user_input = '' while True: user_input = input( 'Pick one: A) Python | B) JavaScript | C) TypeScript [A/B/C]? ') if user_input.upper() == 'A': print('You picked Python') break elif user_input.upper() == 'B': print('You picked JavaScript') break elif user_input.upper() == 'C': print('You picked TypeScript') break else: print('Type a letter A-C') continue

user input multiple choice letters

The code snippet prompts the user to select one of the multiple available choices but uses letters instead of numbers.

We used the str.upper() method to uppercase the input value, so the conditions are met even if the user enters a, b or c.

The str.upper() method returns a copy of the string with all the cased characters converted to uppercase.

main.py
print('a'.upper()) # ๐Ÿ‘‰๏ธ 'A' print('z'.upper()) # ๐Ÿ‘‰๏ธ 'Z'

Once the user enters a valid option, we use the break statement to break out of the while loop.

# Using the inquirer package to select an option with user input

Alternatively, you can use the inquirer package.

Open your terminal in your project's root directory and install inquirer.

shell
pip install inquirer

Now we can import and use the inquirer package.

main.py
import inquirer options = ['python', 'js', 'ts'] questions = [ inquirer.List('language', message="What is your favorite language?", choices=options, ), ] answers = inquirer.prompt(questions) print(answers) print(answers['language'])
The code for this article is available on GitHub

You can use the arrow keys on your keyboard to select one of the options.

python select option input inquirer

Note that the inquirer package is mainly intended to be used on Unix-based platforms (Linux and MacOS).

The package has experimental support for Windows.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev