Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to count the number of uppercase and lowercase letters - Python Program

Example 1 :

def count_case(s): """Count uppercase and lowercase letters.""" upper = sum(1 for ch in s if ch.isupper()) lower = sum(1 for ch in s if ch.islower()) return upper, lower print(count_case("Hello World"))

Output

 
OUTPUT  :
(2, 8)
 

Example 2 : Advanced Program

def count_case_letters(input_string): """ Counts the number of uppercase and lowercase letters in a string. Args: input_string: The string to analyze. Returns: A tuple containing two integers: (uppercase_count, lowercase_count). """ uppercase_count = 0 lowercase_count = 0 for char in input_string: if char.isupper(): uppercase_count += 1 elif char.islower(): lowercase_count += 1 return uppercase_count, lowercase_count # Example Usage: text = "Hello World! 123" upper, lower = count_case_letters(text) print(f"Original string: '{text}'") print(f"Number of uppercase letters: {upper}") print(f"Number of lowercase letters: {lower}")

Output

 
OUTPUT  :
Original string: 'Hello World! 123'
Number of uppercase letters: 2
Number of lowercase letters: 8
 

Explanation:

count_case_letters(input_string) function:

  • This function takes one argument, input_string, which is the string to be processed.
  • It initializes two variables, uppercase_countand lowercase_count, to 0. These variables will store the respective counts.
  • The code then iterates through each charin the input_string.
  • Inside the loop, isupper()checks if the current character is an uppercase letter. If true, uppercase_count is incremented.
  • elif char.islower()checks if the character is a lowercase letter. If true, lowercase_count is incremented. Characters that are neither uppercase nor lowercase (e.g., numbers, spaces, punctuation) are ignored.
  • Finally, the function returns a tuple containing uppercase_countand lowercase_count.