zaro

How to Take Input Until Enter is Pressed in Python?

Published in Input/Output 2 mins read

To take input until the Enter key is pressed in Python, use the built-in input() function repeatedly within a loop. The loop continues until an empty string is received, which signifies that only the Enter key was pressed.

Method: Using a Loop and the input() Function

This is the most straightforward and commonly used method.

inputs = []
while True:
    line = input("Enter input (press Enter to finish): ")
    if line:
        inputs.append(line)
    else:
        break

print("You entered:")
for item in inputs:
    print(item)

Explanation:

  1. inputs = []: Initializes an empty list called inputs to store the user's input.
  2. while True:: Creates an infinite loop that continues until explicitly broken.
  3. line = input("Enter input (press Enter to finish): "): Prompts the user to enter input and stores the entered text (including spaces) in the line variable. The input() function pauses execution until the user presses Enter.
  4. if line:: Checks if the line variable contains any characters (i.e., if the user entered anything before pressing Enter). An empty string evaluates to False in Python.
  5. inputs.append(line): If the line is not empty, it's appended to the inputs list.
  6. else: break: If the line is empty (meaning the user just pressed Enter), the break statement exits the while loop.
  7. Printing the Input: The code then iterates through the inputs list and prints each entered line.

Example Usage:

If the user enters the following:

This is line 1
This is line 2

The output will be:

You entered:
This is line 1
This is line 2

Considerations

  • This method reads input line by line.
  • It's suitable for scenarios where you need to collect multiple lines of text until the user signals the end of input by pressing Enter without typing anything.
  • You can modify the prompt message in the input() function to provide more specific instructions to the user.