Q.Write a program to accept string/sentences from the user till the user enters "END". Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →This program accepts sentences from the user until "END" is entered, saves them to a text file, and then reads the file to display only those sentences that start with an uppercase letter.
When working with files in programming, a common task is to read data from the user, store it persistently, and then process that stored data. This problem combines several fundamental concepts:
- File Input/Output (I/O): How to open a file, write data to it, and read data from it.
- User Input: How to continuously accept input from the user until a specific sentinel value is provided.
- String Manipulation: How to check properties of a string, specifically its first character.
The core idea is to first gather all the user's input and commit it to a file. This ensures that even if the program stops, the data remains. Then, in a separate step, we read back from this file, line by line, and apply a filtering condition (starting with an uppercase letter) before displaying the result.
Here's the Python program to achieve this:
# Define the filename for storing sentences
filename = "user_sentences.txt"
# --- Part 1: Accept input from the user and save to file ---
print("Please enter sentences. Type 'END' (in uppercase) when you are finished.")
# Open the file in write mode ('w').
# The 'with' statement ensures the file is automatically closed even if errors occur.
with open(filename, 'w') as file_writer:
while True:
user_input = input() # Accept a line of input from the user
if user_input == "END":
break # Exit the loop if the user types "END"
# Write the accepted sentence to the file, followed by a newline character.
# This ensures each sentence is on a new line in the file.
file_writer.write(user_input + '\n')
print(f"\nAll sentences (excluding 'END') have been saved to '{filename}'.")
# --- Part 2: Read from the file and display sentences starting with an uppercase alphabet ---
print("\nDisplaying sentences from the file that begin with an uppercase alphabet:")
# Open the file in read mode ('r').
with open(filename, 'r') as file_reader:
for line in file_reader:
# The .strip() method removes leading/trailing whitespace, including the newline character
# that is typically read from the end of each line in a text file.
sentence = line.strip()
# Check if the sentence is not empty and its first character is an uppercase letter.
# An empty string check (`if sentence`) prevents an IndexError if a line was just a newline.
if sentence and sentence[0].isupper():
print(sentence)
Explanation of Key Lines:
-
filename = "user_sentences.txt":- This line defines a string variable
filenameto store the name of the text file. Using a variable makes it easy to change the filename later if needed.
- This line defines a string variable
-
with open(filename, 'w') as file_writer::- This is the standard and recommended way to open files in Python.
open()function is used to establish a connection to the file.filenamespecifies which file to open.'w'is the mode for opening the file. It stands for "write mode". If the fileuser_sentences.txtdoes not exist, it will be created. If it already exists, its contents will be truncated (erased) before writing new data.as file_writerassigns the file object to the variablefile_writer.- The
withstatement acts as a context manager. It automatically handles closing the file (file_writer.close()) once the block of code insidewithis exited, even if an error occurs. This prevents resource leaks.
-
user_input = input():- The
input()function reads a line of text entered by the user from the console and returns it as a string.
- The
-
if user_input == "END": break:- This condition checks if the user has typed the specific string "END". If true, the
breakstatement immediately terminates thewhileloop, stopping further input collection.
- This condition checks if the user has typed the specific string "END". If true, the
-
file_writer.write(user_input + '\n'):- The
write()method of the file object writes the given string to the file. - We append
'\n'(newline character) touser_input. This is crucial becauseinput()does not include the newline character, and without it, all sentences would be written on a single line in the file, making them difficult to read back as individual sentences.
- The
-
with open(filename, 'r') as file_reader::- This opens the same file, but this time in
'r'(read mode). This mode allows us to read the contents of the file without modifying it.
- This opens the same file, but this time in
-
for line in file_reader:: …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.