Python Loops: for & while

Python Tutorial › Control Flow › Loops: for & while

Python Loops: for & while

BeginnerLesson 15 of 4714 min read12 runnable examples

A loop repeats a block of code. Use a for loop to go through every item in a collection, and a while loop to repeat until a condition changes. Loops are behind almost every practice program on this site.

In this lesson
  • Loop over lists, strings and dicts with for
  • Count with range()
  • Repeat until a condition with while
  • Control loops with break, continue and else

The for loop

A for loop takes each item from a collection in turn and runs the block once per item.

Python
browsers = ["chromium", "firefox", "webkit"] for browser in browsers:    print("Testing on", browser)print("All browsers done")
Output
Testing on chromium
Testing on firefox
Testing on webkit
All browsers done

It works with anything you can iterate over, including strings, tuples, sets, dicts and files:

Python
for ch in "SQA":    print(ch)
Output
S
Q
A

Count with range()

range() produces a sequence of numbers on demand. It stops before the end value.

CallNumbers
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 10, 3)0, 3, 6, 9
range(5, 0, -1)5, 4, 3, 2, 1
Python
for i in range(1, 6):    print(i, "squared is", i * i) print(list(range(10, 0, -2)))
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
[10, 8, 6, 4, 2]

Index and value: enumerate()

Python
steps = ["open page", "log in", "add to cart"] for number, step in enumerate(steps, start=1):    print(f"Step {number}: {step}")
Output
Step 1: open page
Step 2: log in
Step 3: add to cart

Two lists side by side: zip()

Python
names = ["Asha", "Ravi", "Meena"]scores = [91, 78, 85] for name, score in zip(names, scores):    print(f"{name:6} {score}")
Output
Asha   91
Ravi   78
Meena  85

Loop over a dictionary

Python
stock = {"pen": 40, "notebook": 0, "bag": 7} for item, qty in stock.items():    status = "out of stock" if qty == 0 else f"{qty} left"    print(item, "-", status)
Output
pen - 40 left
notebook - out of stock
bag - 7 left

The while loop

while repeats as long as its condition is true. Make sure something in the loop changes the condition, or it never stops.

Python
balance = 1000year = 0 while balance < 2000:    balance *= 1.08          # 8% growth per year    year += 1 print(f"Doubled after {year} years: {balance:.2f}")
Output
Doubled after 10 years: 2158.92
Watch out

while True: loops forever unless a break stops it. If a program seems stuck, press Ctrl+C in the terminal to stop it.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and goes to the next item.
Python
numbers = [4, 7, -1, 12, 0, 9] for n in numbers:    if n < 0:        print("skip negative", n)        continue    if n == 0:        print("zero found, stopping")        break    print("processing", n)
Output
processing 4
processing 7
skip negative -1
processing 12
zero found, stopping

else on a loop

A loop’s else block runs only if the loop finished without break. It is perfect for “search, and report if not found”:

Python
users = ["asha", "ravi", "meena"]wanted = "john" for user in users:    if user == wanted:        print("Found", wanted)        breakelse:    print(wanted, "not found")
Output
john not found

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one.

Python
for row in range(1, 4):    for col in range(1, 4):        print(row * col, end="\t")    print()
Output
1	2	3	
2	4	6	
3	6	9	

Patterns are a classic exercise for nested loops:

Python
rows = 4for i in range(1, rows + 1):    print(" " * (rows - i) + "*" * (2 * i - 1))
Output
   *
  ***
 *****
*******

Common loop patterns

Python
prices = [120, 45, 300, 80, 45] total = 0                       # accumulatefor p in prices:    total += p count_cheap = 0                 # count matchesfor p in prices:    if p < 100:        count_cheap += 1 biggest = prices[0]             # track the maximumfor p in prices[1:]:    if p > biggest:        biggest = p print(total, count_cheap, biggest)print(sum(prices), sum(1 for p in prices if p < 100), max(prices))   # built-in shortcuts
Output
590 3 300
590 3 300
Tip

Write the loop yourself while learning, because interviewers and practice programs ask for it. In real code, prefer sum(), max(), min() and any() when they fit.

Check your understanding

Predict the output

total = 0for i in range(1, 10, 2):    if i == 7:        break    total += iprint(total)

Quick quiz

1. What numbers does range(3) produce?

2. When does a loop’s else block run?

3. What does continue do?

4. Which loop fits “keep asking until the user types quit”?

Exercise: digits of a number

Use a while loop to print the sum of the digits of a number and the number reversed.

Input
40721
Expected output
Sum of digits: 14
Reversed: 12704
Hint 1

n % 10 gives the last digit and n // 10 removes it.

Program Practice

Python loops FAQ

What is the difference between a for loop and a while loop?

A for loop goes through the items of a collection or a range, so the number of passes is known. A while loop repeats until its condition becomes false.

How do I loop with an index in Python?

Use enumerate(): for i, item in enumerate(items):. Avoid for i in range(len(items)) unless you really need the number alone.

How do I loop backwards in Python?

Use reversed(items) or range(start, stop, -1), for example for i in range(10, 0, -1):.

Does Python have a do-while loop?

No. Write while True: and break at the end of the body when the condition is met.