Python Loops and Range - Explained
1. What is a Loop?
A loop is used to repeat a block of code multiple times. Python has two types of loops: 'for' and 'while'.
2. Python for loop & range()
Format: for variable in range(start, stop, step):
# code block
Example 1: Print numbers from 1 to 5
for i in range(1, 6):
print(i)
Example 2: Even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
Note:
- range(stop): from 0 to stop-1
- range(start, stop): from start to stop-1
- range(start, stop, step): increment by step
3. Python while loop
Format:
initialization
while condition:
# code block
increment/decrement
Example: Print numbers from 1 to 5
i=1
while i <= 5:
Python Loops and Range - Explained
print(i)
i += 1
4. break and continue
break: exits the loop immediately
for i in range(5):
if i == 3:
break
print(i)
continue: skips the current iteration
for i in range(5):
if i == 2:
continue
print(i)
5. Nested Loops
Loops inside another loop.
Example:
for i in range(1, 4):
for j in range(1, 3):
print(f"i={i}, j={j}")
6. Summary Table
| Loop Type | Use Case | Example Syntax |
|-----------|-----------------------|----------------------------|
| for | Fixed repetitions | for i in range(5): |
| while | Condition-based | while i <= 10: |
| range() | Generates number list | range(start, stop, step) |
Python Loops and Range - Explained
| break | Exit loop early | if condition: break |
| continue | Skip iteration | if condition: continue |