← Learning Hub
Beginner

Loops: for and while

for loops

Computers are great at repeating work. Sending a message to 500 customers, adding up 10,000 sales, checking every product's stock - you write the instructions once and a loop repeats them for every item. Without loops, you'd copy the same lines again and again.

A for loop goes through each item in a list, string or range.

Read it like English: "for each item in this list, do this". In each round, the variable (item) holds the next value. The indented lines are the body of the loop - they run once per item. When the items run out, the loop ends and Python continues with the next unindented line.

Example
You can edit this code.

range(start, stop) gives numbers from start up to (not including) stop:

range is useful when you want to repeat something a fixed number of times, or need counting numbers. range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0). range(1, 11) gives 1 to 10.

Example
You can edit this code.

while loops

A while loop repeats as long as a condition is true.

Use for when you know what to go through (a list, a range). Use while when you don't know how many rounds you need - for example, "keep asking until the user types a valid PIN". Always make sure something inside a while loop eventually makes the condition false, or the loop will run forever.

Example
You can edit this code.

break and continue

Example
You can edit this code.

continue skips the rest of this round and goes to the next item - useful for ignoring bad data. break stops the loop completely - useful when you've found what you were looking for, so there's no need to check the rest.

Use enumerate(list) when you need the position too: for i, item in enumerate(cart):
Key points
  • for repeats code for each item in a list, string or range.
  • while repeats as long as a condition is true - make sure it ends.
  • continue skips one round; break stops the loop.

📝 Test yourself

1. Which numbers does range(1, 4) give?
2. What does break do?
3. Fill in the keyword that skips to the next round of a loop: