Module 3: Control Flow - Conditional Execution and Loops
Loops: `while` and `for`
Loops are used to repeat a block of code multiple times.
-
while
loop: Repeats a block of code as long as a condition isTrue
.count = 0 while count < 5: print(count) count += 1
Be careful to avoid infinite loops by ensuring the condition eventually becomesFalse
. -
for
loop: Iterates over a sequence (like a list, string, or range) or other iterable objects.for letter in "Python": print(letter)
for i in range(5): print(i) # Prints 0, 1, 2, 3, 4
Therange()
function is commonly used withfor
loops to iterate a specific number of times.range(start, stop, step)
generates numbers fromstart
up to (but not including)stop
, incrementing bystep
. Ifstart
is omitted, it defaults to 0. Ifstep
is omitted, it defaults to 1.