Bitpath

Lesson 2 · Unit 02

Loops

while, for, range, break and continue

13 exercisesabout 3 min

What you practise

  • while with a counter, for over range, break and continue, a running total, tracing a loop by hand in a table, the loop that never ends

Try a question from this lesson

Pick one

while works like if, but after the indented lines run, Python goes back up and asks the question again. What does this show?

Python
count = 1
while count <= 3:
    print(count)
    count = count + 1

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

while

A loop repeats a block of code. while repeats its block for as long as its question stays true.

A counting loop has three parts: a start value, a test, and a change that moves towards the end.

count += 1 is short for count = count + 1. There are -= and *= too.

Python
count = 1            # start
while count <= 3:    # test
    print(count)
    count += 1       # change
print("done")        # after the loop

Concept

for and range

A for loop runs its block once for each value it is handed, and puts that value in a name of your choice.

range(4) hands out 0, 1, 2, 3: it starts at 0 and stops just before 4. range(2, 5) starts at 2 and stops just before 5.

No counter to start or change: for does it for you.

Python
for i in range(4):
    print(i)       # 0 1 2 3

for i in range(2, 5):
    print(i)       # 2 3 4

10 more exercises in the app

  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy