How for
Loops Work
- A
for
loop runs a set number of times based on the sequence it iterates over. - It cannot run indefinitely.
Syntax:
for variable in sequence: # Code block to execute
Example: Iterating Over a List
fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(fruit)
Output:
Apple Banana Cherry
Using range()
in a for
Loop
- The
range()
function generates a sequence of numbers. - Used when looping a fixed number of times.
Syntax:
for i in range(start, stop, step): # Code block
Example: Looping a Fixed Number of Times
for i in range(5): print(i)
Output:
0 1 2 3 4
Example: Custom Step Value
for i in range(2, 10, 2): print(i)
Output:
2 4 6 8
Nested for
Loops
- A
for
loop can be inside anotherfor
loop. - Useful for working with multi-dimensional data.
Example:
for i in range(3): for j in range(2): print(f"i: {i}, j: {j}")
Output:
i: 0, j: 0 i: 0, j: 1 i: 1, j: 0 i: 1, j: 1 i: 2, j: 0 i: 2, j: 1
Loop Control Statements: break
and continue
break
statement: Exits the loop early.continue
statement: Skips the current iteration and moves to the next.
Example of break
:
for num in range(10): if num == 5: break # Stops the loop when num is 5 print(num)
Example of continue
:
for num in range(10): if num % 2 == 0: continue # Skips even numbers print(num)