Concepts 🚀 Project 🧮 Labs
🧮 Labs / Python / Loops — for, while, comprehensions

Loops — for, while, comprehensions

for iterates over any iterable. while runs until a condition is false. Comprehensions build lists in one line.

script.py v3.1
Python output click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
🧠 How it works

for variable in iterable: runs the loop body once per item. range(5) produces 0,1,2,3,4. range(2, 5) produces 2,3,4. range(0, 10, 2) produces 0,2,4,6,8. enumerate(iterable) yields (index, value) pairs — use it instead of range(len(iterable)). while condition: runs while condition is True. Risk: infinite loop if condition never becomes False. List comprehension: [expr for var in iter if cond] — faster than a for+append loop. Dict comprehension: {k: v for k, v in pairs}. Set comprehension: {x for x in iter}.

✏️ Try these changes
  • Change range(5) to range(2, 10)
    → loop runs from 2 to 9
  • Change range(5) to range(0, 10, 2)
    → steps by 2: 0,2,4,6,8
  • Change 'while n > 1' to 'while n > 0'
    → extra iteration when n becomes 1
  • Change squares to [x*x for x in range(5) if x % 2 == 0]
    → only squares of evens: [0, 4, 16]
  • Add 'break' inside the for loop after the first print
    → loop exits after first iteration