CodeBlanks Logo Icon CodeBlanks

Summary - Loops

Combine for, while and range to write a multiplication table.

Summary - Loops

In this group you learned for, range, while, break/continue and loop else.

  • for: collection loop.
  • range: number range.
  • while: condition loop.
  • break: exit, continue: skip.
  • else: breakless end.

Now two tasks combine these concepts.

This summary gives a chance to combine loop concepts in a real example.

This summary gives a chance to combine loop concepts in a real example.

This summary gives a chance to combine loop concepts in a real example.

This summary gives a chance to combine loop concepts in a real example.

Practice Sum with for

Assign total = 0. Write for n in [1, 2, 3]: total += n. Print print(total).

Starter code

main.py
# Sum with for

Sample solution

main.py
total = 0
for n in [1, 2, 3]:
    total += n
print(total)

Expected output

6

Practice Count with while

Assign n = 0. Write while n < 5: print(n); n += 1.

Starter code

main.py
# Count with while

Sample solution

main.py
n = 0
while n < 5:
    print(n)
    n += 1

Expected output

0
1
2
3
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is wrong?

  • for is a collection loop
  • break restarts the loop Correct answer
  • while is a condition loop
  • continue skips an iteration

Explanation: break ends the loop, it does not restart it.

2 Complete the range step

Question
for i in range(0, 10, ____):
    print(i)
Answer
for i in range(0, 10, 2):
    print(i)

Explanation: range(0, 10, 2) produces 0, 2, 4, 6, 8.

All lessons in Beginner