Question:hard

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

Solution and Explanation

Step 1: Decide how to read the file:
Using the with statement is safe, because the file closes by itself at the end of the block. We read the file one line at a time, so even a large file works.

Step 2: Decide how to spot a digit:
A character is a digit if it is one of '0' to '9'. We can test this with the membership operator in on the string '0123456789'.

Step 3: Write the function:
def count_digits():
    total = 0
    with open('Space.txt') as f:
        for line in f:
            for ch in line:
                if ch in '0123456789':
                    total += 1
    return total

The outer loop picks each line. The inner loop picks each character of that line. total grows by 1 for each digit found.

Step 4: Verify the count:
The text has 1969, 400 and 2030. That is 4 + 3 + 4 = 11 digits. Running the function on this text printed 11.

Final Answer:
The function returns 11 for the sample file, which is the count of digit characters in Space.txt.
Was this answer helpful?
0