Lesson 6 of 6 · Python

Repeating work with loops

Loops repeat a block of code without making you write the same statement again and again. Learn when to use for, while, range(), break and continue.

Use for when you know what to iterate over

A for loop takes each item from a sequence and runs the indented block once for that item. It works with strings, lists and other iterable objects. The loop variable receives the current item on each pass.

range(5) produces the numbers 0 through 4. The stop value is excluded. You can also provide a start and step, such as range(1, 10, 2), to produce 1, 3, 5, 7 and 9.

Use while for a condition-controlled loop

A while loop repeats as long as its condition is true. Change the state used by that condition inside the loop, otherwise it may never become false and the loop may run forever.

For example, a counter can start at zero and increase by one on every pass. Once it reaches the target value, the condition becomes false and the loop stops.

Control the loop

break exits the nearest loop immediately. continue skips the rest of the current pass and moves to the next one. Use them when they make the loop logic clearer, not as a replacement for a simple condition.

Test loops with small values first. Check the start value, stop condition and update step. Most beginner loop bugs come from an incorrect range boundary or a counter that is never updated.

main.py
for number in range(1, 6):
    print("Number:", number)

for letter in "CODE":
    print(letter)
countdown.py
count = 5
while count > 0:
    print(count)
    count -= 1

print("Go!")

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Print the multiplication table for a number entered by the user, from 1 to 10. Use a for loop and range().

Show a hint
number = int(input("Table for: "))
for i in range(1, 11):
    print(number, "x", i, "=", number * i)

#CodeCampus

Code Campus