Question:medium

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

Show Hint

Use isupper()} and islower()} to efficiently count uppercase and lowercase letters in a string. Combine with open()} for file handling.
Updated On: Jan 13, 2026
Show Solution

Solution and Explanation

def c_words():
    # Open the file Words.txt in read mode
    with open("Words.txt", "r") as file:
        content = file.read()  # Read the entire content of the file
        upper_count = 0  # Initialize uppercase count
        lower_count = 0  # Initialize lowercase count
        
        # Iterate through each character in the content
        for char in content:
            if char.isupper():  # Check for uppercase letters
                upper_count += 1
            elif char.islower():  # Check for lowercase letters
                lower_count += 1
        
        # Display the counts
        print(f"Uppercase letters: {upper_count}")
        print(f"Lowercase letters: {lower_count}")
    
Explanation: The script opens Words.txt for reading and loads its entire content. It then proceeds to examine each character within the content. The isupper() method identifies uppercase letters, while islower() identifies lowercase letters. The script maintains separate counters for both uppercase and lowercase letters and presents these counts upon completion of the character iteration.
Was this answer helpful?
0