Last updated: Apr 9, 2024
Reading timeยท3 min
try/except
To take multiple lines of user input:
while
loop to iterate for as long as the user is typing in values.Enter
without typing in a value, break out of the loop.lines = [] while True: user_input = input() # ๐๏ธ if the user presses Enter without a value, break out of the loop if user_input == '': break else: lines.append(user_input + '\n') # ๐๏ธ prints list of strings print(lines) # ๐๏ธ join list into a string print(''.join(lines))
We used a while
loop to iterate for as long as the user is typing in values.
Enter
without typing in a value to exit out of the while True
loop.This can be any other condition, e.g. you might have a stop word such as done
or quit
.
The break statement breaks out of the innermost enclosing for or while loop.
If the user types in a value, we use the list.append()
method to append the
value and a newline character to a list.
The list.append() method adds an item to the end of the list.
Alternatively, you can use the sys.stdin.readlines()
method to read user input
until EOF.
The readlines()
method will return a list containing the lines.
The user can press CTRL + D
(Unix) or CTRL + Z
(Windows) to exit.
import sys # ๐๏ธ User must press Ctrl + D (Unix) or Ctrl + Z (Windows) to exit print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit') user_input = sys.stdin.readlines() # ๐๏ธ get list of lines print(user_input) # ๐๏ธ join the list items into a string print(''.join(user_input))
stdin
is used for interactive user input.
CTRL + D
(on Unix) or CTRL + Z
on Windows to exit.The readlines()
method returns a list containing the list the user entered.
You can use the str.join() method if you need to join the list of strings into a string.
# a # b # c print(''.join(['a\n', 'b\n', 'c\n']))
If you only need a string containing the lines, use the sys.stdin.read()
method instead.
import sys user_input = sys.stdin.read() print(user_input)
The sys.stdin.read()
method returns a string containing the lines the user
entered.
Alternatively, you can use a try/except statement.
try/except
This is a three-step process:
while
loop to iterate until EOF.except
block and break out of the loop.lines = [] while True: try: lines.append(input()) except EOFError: lines_str = '\n'.join(lines) print(lines_str) break print(lines)
We used a while
loop to iterate until EOF.
If the user presses CTRL + D
(Unix) or CTRL + Z
(Windows), an EOFError
exception is raised and is handled in the except
block.
The break statement breaks out of the
innermost enclosing for
or while
loop.
You can learn more about the related topics by checking out the following tutorials: