Python Program to Count Uppercase and Lowercase in a String

1. Introduction

Analyzing text often requires knowing the case of the characters within it. Counting uppercase and lowercase letters is a fundamental operation in text processing. Python makes this task easy, as we will demonstrate in this program.

Uppercase letters are the capital letters of the alphabet, while lowercase letters are the smaller forms. In a given string, each letter can be classified as either uppercase or lowercase, and Python's string methods can identify these cases.

2. Program Steps

1. Define the string to be analyzed.

2. Initialize counters for both uppercase and lowercase letters to zero.

3. Loop over each character in the string, incrementing the appropriate counter when an uppercase or lowercase letter is encountered.

4. Output the counts of uppercase and lowercase letters.

3. Code Program

# Define the string to be analyzed
input_string = "Python is FUN!"

# Initialize counters for uppercase and lowercase
uppercase_count = 0
lowercase_count = 0

# Loop over each character and count upper and lower case
for char in input_string:
    if char.isupper():
        uppercase_count += 1
    elif char.islower():
        lowercase_count += 1

# Print the counts
print(f"Uppercase Count: {uppercase_count}")
print(f"Lowercase Count: {lowercase_count}")

Output:

Uppercase Count: 3
Lowercase Count: 8

Explanation:

1. input_string is the text we want to examine.

2. uppercase_count and lowercase_count are set to 0 and serve as counters for uppercase and lowercase letters, respectively.

3. A for loop iterates through each char in input_string.

4. isupper() and islower() methods determine if a character is uppercase or lowercase.

5. If char.isupper() is True, uppercase_count is incremented; if char.islower() is True, lowercase_count is incremented.

6. Characters that are neither uppercase nor lowercase (like spaces and punctuation) are ignored.

7. After iterating through the string, print statements output the total counts for uppercase and lowercase letters, which are 3 and 8, respectively, for the given input_string.

Comments