Take infinite user input values in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Take infinite user input values in Python #

To take infinite user input values:

  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
# ✅ When taking strings as input my_list = [] while True: user_input = input('Enter a color: ') if user_input == '': break my_list.append(user_input) print(my_list) # --------------------------------------------- # ✅ When taking 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 infinite inputs

We used a while loop to take user input while iterating an infinite 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 declared an empty list variable that will store the input values.

main.py
my_list = [] while True: user_input = input('Enter a color: ') 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 3 input values are stored in the list.

main.py
my_list = [] while True: if len(my_list) >= 3: break user_input = input('Enter a color: ') 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 infinite user 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 infinite inputs numeric values

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.