Test Index

CBSE Class 12 Computer Science 2025 Paper Compartment Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 29 of 37
Marks: +1, -0
(a) Write a Python function that displays all the lines ending with a dot (.) from a text file "Colors.txt". For example, if the file contains :
White is a mix of seven colors.
What are these seven colors ?
VIBGYOR – violet, indigo, blue, green, orange and red.
When we mix all these colors we just get one light
which is the WHITE light.
Then the output should be :
White is a mix of seven colors.
VIBGYOR – violet, indigo, blue, green, orange and red.
which is the WHITE light.
(Hint : You will have to ignore trailing white spaces to check the last character)
OR
(b) Write a function in Python to display the line which has the maximum number of vowels from a text file, "Novel.txt".
Solution:  
(a)
Concept: Read the file line by line. Each line read from a file ends with \n (and may have extra spaces), so rstrip() removes the trailing white space first; then endswith(".") checks the last character.
def show_dot_lines():
f = open("Colors.txt", "r")
for line in f:
line = line.rstrip() # remove trailing spaces and '\n'
if line.endswith("."): # last character is a dot
print(line)
f.close()
show_dot_lines()
For the sample file this prints the 1st, 3rd and 5th lines, exactly as the expected output shows.
OR (b)
Concept: Count the vowels (both cases) in every line and remember the line with the largest count seen so far.
def max_vowel_line():
f = open("Novel.txt", "r")
maxline = ""
maxcount = -1
for line in f:
count = 0
for ch in line: # count vowels in this line
if ch in "aeiouAEIOU":
count += 1
if count > maxcount: # keep the line with most vowels
maxcount = count
maxline = line
f.close()
print(maxline.rstrip())
max_vowel_line()
Key point: Initialise the counter outside the file loop and reset the vowel count to 0 for every new line.
© examsnet.com
Advertisements
Go to Question: