Last updated: Apr 9, 2024
Reading timeยท5 min
To use user input to select an option from a list:
input()
function to take user input.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)
The example lets the user select one of the options in the list.
python
, js
, ts
, but you could also tweak this and have the user type a number that corresponds to a list item.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 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
.
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.
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
.
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])
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.
To define a multiple-choice question with user input:
input()
function to take input from the user.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
We used a while True
loop to iterate until the user types in one of the
options.
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.
input()
function is always guaranteed to return a string, even if the user enters a number.You can also use letters for the options.
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
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.
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.
Alternatively, you can use the inquirer package.
Open your terminal in your project's root directory and install inquirer
.
pip install inquirer
Now we can import and use the inquirer
package.
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'])
You can use the arrow keys on your keyboard to select one of the options.
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.
You can learn more about the related topics by checking out the following tutorials: