Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.
python
Program to accept sentences and display those starting with uppercase
fileobject = open("data.txt", "w") while True: sentence = input("Enter a sentence (or 'END' to stop): ") if sentence == "END": break fileobject.write(sentence + "\n") fileobject.close()
Reading file and displaying sentences starting with uppercase
fileobject = open("data.txt", "r") print("\nSentences beginning with uppercase alphabet:") for line in fileobject: line = line.strip() if line and line[0].isupper(): print(line) fileobject.close()
Explanation: The program first opens a text file in write mode using open() function. A while loop continuously accepts sentences from the user until "END" is entered. Each sentence is written to the file followed by a newline character \n.
After closing the file, it is reopened in read mode. The program then iterates through each line using a for loop. The strip() method removes any leading or trailing whitespace. The condition line[0].isupper() checks if the first character of the line is an uppercase alphabet. Only those sentences satisfying this condition are displayed on the screen.
Explanation
This question tests the student's understanding of file handling operations in Python - opening files in write and read modes, writing data using loops, and applying string methods like isupper() to filter content. The program structure follows the pattern shown in Program 2-5 and Program 2-3 from the textbook context.
Solution Steps
Step 1: Open a text file in write mode to store sentences.
Step 2: Use a while loop to accept sentences until user enters 'END'.
Step 3: Write each sentence to the file with newline character.
Step 4: Close the file after writing all data.
Step 5: Reopen the file in read mode.
Step 6: Iterate through each line and check if first character is uppercase using isupper().
Step 7: Display only those sentences that begin with uppercase alphabet.