Accept input until Enter is pressed in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Accept input until Enter is pressed in Python #

To accept input until the Enter key is pressed:

  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 the user presses Enter.
main.py
# ✅ When taking strings as input my_list = [] while True: user_input = input('Enter a string: ') if user_input == '': print('User pressed enter') 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 == '': print('User pressed enter') break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

accept input until enter pressed

We used a while loop to take user input while iterating an arbitrary 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.

main.py
my_list = [] while True: user_input = input('Enter a string: ') if user_input == '': print('User pressed enter') break my_list.append(user_input) print(my_list)
If the user presses Enter, the user_input variable stores an empty string and we break out of the while loop.

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

Otherwise, we append the input value to the list.

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

Here is an example that takes an arbitrary number of user input values of type integer until the user presses Enter.

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

accept input until enter pressed 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.