Menu
Courses / python basic / Loops & Iteration

Loops & Iteration

06 / 10 Part of python basic




 

    🔁 Topic 05 · Iteration
 

 


    Loops & Iteration
 


 


    Repeat actions efficiently using for and while loops, and control iteration with break, continue, and handy built-ins like enumerate and zip.
 


 

    ⏱ ~40 min
    🟢 Beginner
    🔄 Core skill
 


 
 

   

     
     

for Loop


   

   

The for loop iterates over any sequence: lists, strings, ranges, tuples, and more.


   

     

        for_loop.py
     

     
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Iterate with range
for i in range(5):           # 0,1,2,3,4
    print(i)

# range(start, stop, step)
for i in range(0, 10, 2):  # 0,2,4,6,8
    print(i)

   

 


 
 

   

     
     

while Loop


   

   

Runs as long as a condition stays true. Always ensure the condition eventually becomes false to avoid an infinite loop.


   

     

        while_loop.py
     

     
count = 0
while count < 5:
    print(f"count = {count}")
    count += 1
# Prints count = 0 through count = 4

   

   

      ⚠️ Infinite loop risk
     

If the condition never becomes False the program hangs. Press Ctrl+C to interrupt. Always verify the loop variable changes each iteration.


   

 


 
 

   

     
     

break and continue


   

   

break exits the loop immediately. continue skips the rest of the current iteration and moves to the next.


   

     

        break_continue.py
     

     
# break — stop at first positive even number
for n in range(10):
    if n % 2 == 0 and n > 0:
        print(f"Found: {n}")
        break             # prints 2, then exits

# continue — skip odd numbers
for n in range(6):
    if n % 2 != 0:
        continue
    print(n)           # 0, 2, 4

   

 


 
 

   

     
     

enumerate & zip


   

   

enumerate gives index + value in each iteration. zip pairs two sequences together.


   

     

        enum_zip.py
     

     
items = ["a", "b", "c"]
for idx, val in enumerate(items):
    print(idx, val)   # 0 a · 1 b · 2 c

names  = ["Alice", "Bob"]
scores = [90, 85]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

   

 


 
 

   

     
     

List Comprehensions


   

   

A concise, readable way to build a new list by transforming or filtering an existing sequence.


   

     

        list_comp.py
     

     
# Standard loop
squares = []
for x in range(5):
    squares.append(x ** 2)

# Same thing as comprehension
squares = [x ** 2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

# With filter
evens = [x for x in range(10) if x % 2 == 0]