Repaso
EspaƱol
PythonFoundationsPY-66

What does this loop print?

for n in [1, 2, 3]:
    print(n * 2)

Options

  1. 1 2 3 (one per line)
  2. 2, 4 and 6 (one per line) (Correct option)
  3. 6 (the sum, printed once)
  4. [2, 4, 6] (printed as a list)

Answer

2, 4 and 6 (one per line)

Why

A for loop repeats a block once for each item of a collection.

First n is 1 and it prints 1 * 2 = 2, then n is 2 and it prints 4, then n is 3 and it prints 6.

Each print writes on its own line. It does not build a list; for that you would use a list comprehension.

Remember

for item in collection: runs once per item.

Key terms

Practice this question in Repaso