0%

Repeating Work with Loops · practice

Loop Over a String

In Chapter 4 you learned that a is an ordered sequence of characters. A for works on any ordered sequence, so it works on strings too.

Try it

Three characters, three lines. Python hands you one character at a time, in order, from the first to the last.

This is the same loop you already know. Only the thing being walked through has changed.

Every character counts

A string does not contain only letters. Spaces and punctuation are characters too, and the loop visits them like any other:

Try it

The brackets make the space visible as its own line. When a character count surprises you, this is a quick way to see exactly what is in the string.

Because of this, character or char is often a better loop name than letter. Use letter when you know the string really does hold letters.

Compare it to indexing

You could reach the same characters with the tools from Chapter 4:

word = "sky"
print(word[0])
print(word[1])
print(word[2])

That works, and it has the same weakness as the four print lines from the organizer. It only fits a three-character string. The loop fits any string:

Try it

Reach for indexing when you want one particular position. Reach for a loop when you want each in order.

Decide on every pass

The loop body can hold any instructions, including an statement. That combination is where loops start to feel powerful: Python asks the question once per character.

Try it

Look carefully at the indentation, because there are now two levels:

for character in "melody":      <- gives character its next value on each pass
    if character in vowels:     <- one level in: runs on every pass
        print(...)              <- two levels in: runs only when the test is True

The if line is indented because it is part of the loop body. The print line is indented twice because it belongs to the if. Python uses those levels to decide what belongs to what, so getting them right is not a style preference.

An if inside a loop does not stop the loop. When the test is False, Python skips that indented line and moves on to the next character.

What does this code print?

for character in "ab c":
    print(f"<{character}>")

In this loop, how many times does print run?

digits = ["1", "2", "3"]
for character in "a1b2":
    if character in digits:
        print(character)

In the exercise, walk through a phrase, pick out its vowels, and report how many characters you checked.

Task

The phrase and vowels values are already written for you. Complete the program so it:

  • over phrase using character as the loop ;

  • prints the uppercase version of each character that appears in the vowels , one per line;

  • keeps the final count line, which runs once after the loop.

Expected output:

O
A
I
U
Characters checked: 18

Use .upper() on the character you print. Do not change phrase or vowels.