What will be the output of the following program?
f=open("comp.txt","r")
for line in f:
words=line.split()
for i in words:
for letter in i :
if(letter.isdigit()):
print(letter)
What will be the output of the following program?
f=open("comp.txt","r")
for line in f:
words=line.split()
for i in words:
for letter in i :
if(letter.isdigit()):
print(letter)
Solution
The file is read line by line, each line is split into words, and each word is checked letter by letter. Only a character for which letter.isdigit() is True gets printed, so the program outputs only the digits found in the file.
Each digit is printed on its own line, so a number like 125 appears as 1, 2, 5 on separate lines.
Options 1 and 4: the program never prints a whole word or line, only single characters that pass the digit test.
Option 3: isdigit() selects digits, not alphabets (that would be isalpha()).
Related questions:
2026: 21 May Shift 1
2025: 13 May Shift 2
2025: 21 May Shift 1
2025: 14 May Shift 1