Skip to content
Exercises · Q8

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.

Puducherry CbseNCERTSubjective· 3mImportance★★★★★
55% · 12/22 Questions
🔒 Locked · start free trial →

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:

  1. File Input/Output (I/O): How to open a file, write data to it, and read data from it.
  2. User Input: How to continuously accept input from the user until a specific sentinel value is provided.
  3. 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:

  1. filename = "user_sentences.txt":

    • This line defines a string variable filename to store the name of the text file. Using a variable makes it easy to change the filename later if needed.
  2. 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.
    • filename specifies which file to open.
    • 'w' is the mode for opening the file. It stands for "write mode". If the file user_sentences.txt does not exist, it will be created. If it already exists, its contents will be truncated (erased) before writing new data.
    • as file_writer assigns the file object to the variable file_writer.
    • The with statement acts as a context manager. It automatically handles closing the file (file_writer.close()) once the block of code inside with is exited, even if an error occurs. This prevents resource leaks.
  3. user_input = input():

    • The input() function reads a line of text entered by the user from the console and returns it as a string.
  4. if user_input == "END": break:

    • This condition checks if the user has typed the specific string "END". If true, the break statement immediately terminates the while loop, stopping further input collection.
  5. 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) to user_input. This is crucial because input() 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.
  6. 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.
  7. 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.