For Loops and range()
A for loop iterates over a sequence (like a list, string, or range of numbers) and executes a block of code for each item in the sequence.
The range() function generates a sequence of numbers and is commonly used with for loops when you need to repeat something a specific number of times.
Example
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating over a string
for char in "Python":
print(char, end=" ")
print() # P y t h o n
# Using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i, end=" ")
print() # 0 1 2 3 4
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i, end=" ")
print() # 2 3 4 5 6 7
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step of 2)
print(i, end=" ")
print() # 0 2 4 6 8 - range(n) — generates numbers from 0 to n-1
- range(start, stop) — generates numbers from start to stop-1
- range(start, stop, step) — generates numbers with a custom step
- The loop variable takes the value of each item one at a time
Try For Loops
JavaScript
# Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print("---")
# Loop with range
for i in range(1, 6):
print(f"{i} x 5 = {i * 5}") Notes
- Unlike many other languages, Python's for loop doesn't use a counter variable by default — it iterates directly over items in a sequence, which is cleaner and less error-prone.
While Loops, Break, and Continue
A while loop keeps executing as long as its condition is True. Be careful to ensure the condition eventually becomes False, or you'll create an infinite loop.
The 'break' statement exits the loop immediately, and 'continue' skips the rest of the current iteration and jumps to the next one.
Example
# While loop
count = 0
while count < 5:
print(count, end=" ")
count += 1
print() # 0 1 2 3 4
# Break — exit the loop early
for i in range(10):
if i == 5:
break
print(i, end=" ")
print() # 0 1 2 3 4
# Continue — skip current iteration
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i, end=" ")
print() # 1 3 5 7 9
# Nested loops
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}x{j}={i*j}", end=" ")
print() # New line after each row - while condition: — runs as long as condition is True
- break — immediately exits the innermost loop
- continue — skips to the next iteration of the loop
- Always ensure while loops have a way to terminate
Try While Loops
JavaScript
# Countdown with while
count = 5
while count > 0:
print(count, end=" ")
count -= 1
print("Go!")
# Skip even numbers with continue
print("Odd numbers:")
for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=" ") Notes
- Python also supports an 'else' clause on loops. The else block runs when the loop completes normally (without hitting a break). This is unique to Python.
