Write a Python program that repeatedly reads lines from standard input until anEOFError is raised, and then outputs those lines in reverse order
Question
Write a Python program that repeatedly reads lines from standard input until anEOFError is raised, and then outputs those lines in reverse order
Solution
Sure, here is a simple Python program that reads lines from standard input until an EOFError is raised, and then outputs those lines in reverse order:
lines = []
try:
while True:
lines.append(input())
except EOFError:
for line in reversed(lines):
print(line)
Here's how it works:
- We start by initializing an empty list
linesto store the lines of input. - The
tryblock starts a section of code that might raise an exception. In this case, we're looking for anEOFError, which is raised when theinput()function hits an end-of-file condition (EOF) without reading any data. - Inside the
tryblock, we start an infinite loop that repeatedly reads a line of input and appends it to thelineslist. - If an
EOFErroris raised, the loop is immediately exited and we move on to theexceptblock. - In the
exceptblock, we iterate over thelineslist in reverse order (using thereversed()function) and print each line.
Please note that in most systems, you can signal an EOF condition in the terminal by pressing Ctrl+D (or Ctrl+Z on Windows).
Similar Questions
Johnny is developing a tool that manipulates the text files efficiently. Your task is to assist johnny to create a Python program that reads a text file (InputData1.txt) and prints each line in reverse order. Sample Test Cases Test Case 1: Expected Output: .ylgu·naht·retteb·si·lufituaeB .ticilpmi·naht·retteb·si·ticilpxE .xelpmoc·naht·retteb·si·elpmiS .detacilpmoc·naht·retteb·si·xelpmoC .detsen·naht·retteb·si·talF .esned·naht·retteb·si·esrapS .stnuoc·ytilibadaeR
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.Ex: If the input is:Hello thereHeydonethe output is:ereht olleHyeH
Write a python program that traverses through an input string and prints its characters indifferent lines – two characters per line
Write a Python program to read a file line by line store it into an array.
66.1.6. Print each line of a file in reverse order. 00:57 Write a program to print each line of a file in reverse order. Note: take the input file name from the use
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.