Tojra
Tojra

Reputation: 683

Reading unknown number of lines from console

I have to read unknown number of lines from stdin in python3. Is there a way to do this without any modules? One more question: How to denote end of input for multiple lines in python3?

Upvotes: 4

Views: 4009

Answers (2)

Nikhileswar Komati
Nikhileswar Komati

Reputation: 31

We can use try and except in the following way

while True:
    try:
        n = int(input())
        # Perform your operations
    except EOFError:
        # You can denote the end of input here using a print statement
        break

Upvotes: 3

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Try something like this

a_lst = []          # Start with empty list
while True:
    a_str = input('Enter item (empty str to exit): ')
    if not a_str:   # Exit on empty string.
        break
    a_lst.append(a_str)
print(a_lst)

Upvotes: 3

Related Questions