The For Loop

Until now, doing something to five items meant writing five lines. A for loop writes it once and runs it for every item in an iterable.

Read it as a sentence: for each item in this collection, do this.

Walking a collection

PYTHON

for item in items:
    print(item)

JAVASCRIPT

for (const item of items) {
  console.log(item);
}
Compare → The same operation with different scaffolding. Python marks the loop body with a colon and INDENTATION, the indentation IS the syntax. JavaScript uses parentheses and curly braces, and needs the word `of`. Both walk the collection one item at a time.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Three lines of output from one print statement. Add two more cities, notice the loop needs no changes at all.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Indentation is not decoration in Python

The indented lines under `for ... :` are the loop body. Un-indent a line and it runs once, after the loop finishes. Python beginners lose hours to this. JavaScript uses braces, so its indentation is only for humans, but indent it anyway, for the humans.

EXAMPLE
loading editor…
YOUR TURN
Your turn → The loop variable holds a different value each pass. Change the body so it prints each number squared instead, then add 10 to the list.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Counting Loops and Ranges →
← Back