Sprint 2 - Iterations (Python)
Iterations in Python
- ✨ Iterations in Python ✨
- What are Iterations?
- The
for
Loop - Loop Control Statements
- Nested Loops
-
enumerate()
for Indexed Iteration
- Interactive Demo
- Learn Iterations (Loops)
- About Iteration in Python
- For Loop Example (
for i in range(n)
) - While Loop Example (
while condition
)
✨ Iterations in Python ✨
What are Iterations?
Iteration means repeating a set of instructions multiple times. In Python, iteration is most often done with loops, which let us run the same block of code several times.
There are two main kinds of loops:
for
loops → iterate over items in a sequence (list, string, range, etc.)while
loops → keep repeating as long as a condition isTrue
The for
Loop
A for
loop goes through items in a sequence one by one.
# Example: Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
We can also iterate over numbers with
range()
:
for i in range(5): # counts from 0 to 4
print(i)
0
1
2
3
4
The While
Loop
A While
loop runs until its condition becomes False
:
count = 0
while count < 5:
print("Count is:", count)
count += 1
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop Control Statements
We can control loops using special keywords:
break
→ stop the loop completelycontinue
→ skip to the next iterationpass
→ do nothing (acts as a placeholder)
Nested Loops
A loop inside another loop:
for i in range(2): # outer loop
for j in range(3): # inner loop
print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
enumerate()
for Indexed Iteration
When looping over lists, we often need both the index and the item.
enumerate()
gives us both at the same time.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
Interactive Demo
Learn Iterations (Loops)
About Iteration in Python
Iteration means repeating a block of code multiple times. Python provides two main loop structures:
for
loops – repeat a block for each item in a sequence or range.while
loops – repeat a block as long as a condition isTrue
.
For Loop Example (for i in range(n)
)
This loop prints numbers from 0
to n-1
.
While Loop Example (while condition
)
This loop keeps adding numbers until the sum exceeds a limit.