←Previous page

05LOOPS · LOOP OVER WORDS

One letter at a time.

A word is a row of letters. for can walk through it, one letter on each turn.

IN REAL LIFE

You already spell things.

Every letter gets its own turn, from the first to the last.

Spelling bee

You say the word one letter at a time: c, a, t.

Find the letter

Look for every A on a sign. You check each letter, one by one.

Count your name

Raise one finger for each letter of your name. How many fingers?

LOOK FIRST

for works with words too.

Same for, new thing

for toy in toys: walked through a list. for letter in word: walks through a word.

One letter per turn

The box letter holds s, then u, then n.

Spaces count

A space is a letter too. It gets its own turn.

LOOK FIRST

Walk through a word.

Read each line and its note.

word = "sun"A text box with 3 letters.
for letter in word:letter is a box. Each turn it holds the next letter: s, then u, then n.
print(letter)Shows one letter on each turn.
print("done!")Runs once, after the loop.

RUN IT

Help PyBot spell its name.

Guess first. Then run real Python and check.

1

Guess the result

name = "PyBot" for letter in name: print(letter)

How many lines will Python show?

spell.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide ♥

Pyodide 314.0.3 runs CPython in your browser with WebAssembly.

Open-source under the Mozilla Public License 2.0. License

Now change one thing: Change PyBot to your name. Run again and count the lines.

YOUR TURN

Walk through words.

Try each tiny question. A wrong answer becomes something to review.

0Completed
9Not tried
0Review
01

Spell it out

PyBot spells dog out loud: d, o, g.

How many turns does that take?

02

What shows?

for letter in "hi": print(letter)

What does Python show?

03

Count the letters

count = 0 for letter in "robot": count = count + 1 print(count)

What does Python show?

04

Spaces count

for letter in "a b": print(letter)

How many turns does the loop take?

05

Find the o's

count = 0 for letter in "robot": if letter == "o": count = count + 1 print(count)

What does Python show?

06

Backwards

new = "" for letter in "abc": new = letter + new print(new)

What does Python show?

07

Words or letters?

for word in ["hi", "yo"]: print(word)

How many turns does the loop take?

08

Fix PyBot's code

PyBot wants to spell sun, one letter per line, but it shows the whole word 3 times. Fix the print line.

Goal output
s
u
n
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

for can walk through a word, one letter on each turn.

Next, you will put a loop inside another loop.