Exercise 5.1
← Previous Module 5: Dictionaries & Sets Next →
Statement
Solution

Python Exercise 5.1: Character Counter

Use a dictionary to count how many times each character appears in a string.

Your program should:

  • Ask the user for a string input.
  • Create a dictionary where keys are characters and values are their counts.
  • Print the character counts in a readable format.
  • Handle both uppercase and lowercase characters (case-sensitive or insensitive, your choice).

Sample Interaction:

Input
Output
hello world
Enter a string: hello world Character counts: h: 1 e: 1 l: 3 o: 2 : 1 w: 1 r: 1 d: 1

Solution

Here is one way to solve this using a dictionary.

# Get input text = input("Enter a string: ") # Initialize dictionary char_count = {} # Count characters for char in text: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 # Print results print("Character counts:") for char, count in char_count.items(): print(f"{char}: {count}")

Key Concepts:

  • Dictionaries store key-value pairs, perfect for counting.
  • Use in to check if a key exists.
  • .items() returns key-value pairs for iteration.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top