Take an unknown number of inputs in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Take an unknown number of inputs in Python #

To take an unknown number of inputs:

  1. Declare a variable that stores an empty list.
  2. Use a while loop to iterate an arbitrary number of times.
  3. Append each user input value to the list.
  4. Break out of the while loop when a condition is met.
main.py
# ✅ Take an unknown number of strings as input my_list = [] while True: user_input = input('Enter a string: ') if user_input == '': break my_list.append(user_input) print(my_list) # --------------------------------------------- # ✅ Take an unknown number of integers as input my_list = [] while True: user_input = input('Enter a number: ') if user_input == '': break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

take unknown number of inputs

We used a while loop to take user input while iterating an unknown number of times.

The only way to break out of a while True loop is to use a break statement or to raise an exception.

We first declared an empty list that will store the input values.

main.py
my_list = [] while True: user_input = input('Enter a string: ') if user_input == '': break my_list.append(user_input) print(my_list)
On each iteration, we check if the user pressed Enter without typing in a value to break out of the while loop.

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

This could be any other condition. For example, you can check if the user typed done.

Here is an example that breaks out of the loop if at least 2 input values are stored in the list.

main.py
my_list = [] while True: if len(my_list) >= 2: break user_input = input('Enter a string: ') my_list.append(user_input) print(my_list)

The list.append() method adds an item to the end of the list.

Here is an example that takes an unknown number of input values of type integer.

main.py
my_list = [] while True: user_input = input('Enter a number: ') if user_input == '': break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

take unknown number of numeric inputs

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

The function then reads the line from input, converts it to a string and returns the result.

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

We used the int() class to convert each string to an integer.

The try/except statement is used to handle the ValueError that is raised if an invalid integer is passed to the int() class.

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.