Multiple choice question with user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

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

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.

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.