Lesson ยท 10 min
Loops
Do it again
A loop runs the same code many times.
The for loop and range
A for loop takes each value from a sequence, one after the other. The range function makes a sequence of numbers.
for i in range(3):
print("Pass number", i)
This prints passes 0, 1, and 2. range has three forms:
| Code | Numbers |
|---|---|
range(4) |
0, 1, 2, 3 |
range(1, 4) |
1, 2, 3 |
range(0, 10, 3) |
0, 3, 6, 9 |
The end number is never included. The third number is the step.
Like if, a for line ends with a colon, and the loop body is indented.
The while loop
A while loop has only a condition. You make the counter yourself, and you change it inside the loop.
n = 3
while n > 0:
print(n)
n -= 1
If the condition never becomes false, the loop never ends. Here, if you forget n -= 1, the loop runs forever. Absolute Path stops code that runs for too long, but a loop that never ends is always a bug.
Keeping a running total
total = 0
for i in range(1, 4):
total += i # the same as total = total + i
print(total) # 6
Numbers and text
You cannot join a number to text with +. Change the number to text with str(): "Pass " + str(3). An f-string does it for you: f"Pass {3}".
Your turn
Some tasks print lines, and some tasks use functions. Do them in order.
Tasks
4 to do
Task 1, not checked yet. Use a
forloop withrangeto print the numbers1to5, one number on each line.Task 2, not checked yet. In
sum_to, add the numbers from1tonwith a loop, and return the sum.sum_to(4)is1 + 2 + 3 + 4, which is10.Task 3, not checked yet. In
count_down, use awhileloop to build the text of the numbers fromstartdown to1, separated by commas.count_down(3)returns'3,2,1'.Task 4, not checked yet. Print the even numbers from
2to10, one on each line. Giverangea third value, the step.
Task 1 of 4
Use a for loop with range to print the numbers 1 to 5, one number on each line.