──────────────────────────────────────

19. Message Lab · Measure a Message

Loop over characters and count the ones that meet a condition.

Lesson files · lessons/strings-and-messages/count-characters

Before you start
- Use a for loop to visit values in order.
- Update a total inside a loop.
- Use if to run a line only when its condition is true.

By the end
- Use a for loop to visit every character in a string.
- Use isdecimal() to decide when to increase a digit count.
- Trace the count for a message with both letters and digits.

Where you can use it
Check how many digits are in a locker code. Visit each character and count digits even when the code mixes letters and numbers.

A for loop over a string visits one character at a time. The example lowercases the word and uses char in "aeiou" to test whether each character appears among the five vowels. Add one to the count each time that test is true.

For the digit challenge, use char.isdecimal() as the test. It returns True when the character is a decimal digit, such as 7. In B2 T17, the counter increases at 2, 1 and 7.

Predict
How does the example handle an uppercase vowel?
- It lowercases before testing.
- It skips uppercase letters.

Worked example (example.py)

count = 0
for char in "BEacon".lower():
    if char in "aeiou":
        count += 1
print(count)


Example result
3

Read a message and print the number of digits. Use char.isdecimal() on each character.

Starter program (starter.py)

count = 0
for char in "BEacon".lower():
    if char in "aeiou":
        count += 1
print(count)


Hint
Keep the counter outside the loop. Increase it inside the if.

Case 1. Try the sample
Input
B2 T17
Expected output
3

Case 2. No digits
Input
All clear
Expected output
0

Stretch
Add a second counter for spaces.

Reflect
What is the difference between counting digits and converting an entire message to int?

Check your prediction
It lowercases before testing. lower() turns E into e, which appears in the string of vowels.
