Python

Lesson 5 of 10

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

  1. Task 1, not checked yet. Use a for loop with range to print the numbers 1 to 5, one number on each line.

  2. Task 2, not checked yet. In sum_to, add the numbers from 1 to n with a loop, and return the sum. sum_to(4) is 1 + 2 + 3 + 4, which is 10.

  3. Task 3, not checked yet. In count_down, use a while loop to build the text of the numbers from start down to 1, separated by commas. count_down(3) returns '3,2,1'.

  4. Task 4, not checked yet. Print the even numbers from 2 to 10, one on each line. Give range a 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.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.