Question:

Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". For example, if the file contains:

Space exploration has unlocked incredible advancements in technology and science. Since the first moon landing in 1969, space agencies have sent probes to Mars, Jupiter and beyond. The ISS, orbiting Earth at about 400 km, serves as a hub for research. With missions planned for 2030, humanity’s cosmic journey continues!

Then the function should return 11.

Show Hint

Read the file, loop over every character and count it when isdigit() is True. Return the count at the end.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Plan the function:
We must read the whole text file and count the characters that are digits. The function then returns this count.
Python gives the string method isdigit(). It returns True for a character like '4' and False for a letter or a symbol.

Step 2: Write the function line by line:
def count_digits():
    f = open('Space.txt', 'r')
    data = f.read()
    f.close()
    count = 0
    for ch in data:
        if ch.isdigit():
            count += 1
    return count

open() opens the file in read mode. read() puts the full text in the string data. close() releases the file.
count starts at 0. The loop visits every character and adds 1 when the character is a digit.

Step 3: Check with the sample text:
The digits in the text are 1969 (4 digits), 400 (3 digits) and 2030 (4 digits).
4 + 3 + 4 = 11. I ran this function on the sample text and it returned 11.

Final Answer:
The function count_digits() above returns the number of digits in Space.txt, which is 11 for the given file.
Was this answer helpful?
0
0

Top CBSE CLASS XII file handling Questions