Skip to content
Question

Q.(A) Write a user defined function in Python named showInLines() which reads contents of a text file named STORY.TXT and displays every sentence in a separate line. Assume that a sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!). For example, if the content of file STORY.TXT is as follows: Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell? Then the function should display the file's content as follows: Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell?

(OR)
(B) Write a function, c_words() in Python that separately counts and displays the number of uppercase and lowercase alphabets in a text file, Words.txt.
CBSECBSE Class XII Board 2024Subjective· 3mImportance★★★★★
🔒 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 →

Part (a): showInLines() prints each sentence of STORY.TXT on its own line, splitting on ., ?, !. Part (b): c_words() counts and displays the number of uppercase and lowercase alphabets in Words.txt.

Part (a)

Read the file's content, then scan it character by character. Accumulate characters into a sentence string; whenever the current character is one of the terminators ., ?, !, print the sentence (stripped of surrounding spaces) and reset. A final check prints any trailing text if the file does not end in a terminator.

def showInLines():
    f = open("STORY.TXT", "r")
    content = f.read()
    sentence = ""
    for ch in content:
        sentence += ch
        if ch in ".?!":
            print(sentence.strip())
            sentence = ""
    if sentence.strip():
        print(sentence.strip())
    f.close()

With the sample content, expected output:

Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell? …

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.