Lesson 2 · Unit 02
Loops
while, for, range, break and continue
What you practise
whilewith a counter,foroverrange,breakandcontinue, 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?
count = 1
while count <= 3:
print(count)
count = count + 1Correct answer
1, 2 and 3
Why
Each pass shows count and then adds 1 to it. After the third pass count is 4, the question 4 <= 3 is false, and the loop ends. Nothing is shown for 4.
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.
count = 1 # start
while count <= 3: # test
print(count)
count += 1 # change
print("done") # after the loopConcept
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.
for i in range(4):
print(i) # 0 1 2 3
for i in range(2, 5):
print(i) # 2 3 410 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.