Loops (for and while)¶
Loops are used to execute a block of code repeatedly. Python provides two basic loop statements: for and while.
1. The for Loop¶
In Python, the for statement iterates over the items of any sequence (such as a list, tuple, or string) in the order that they appear.
Syntax¶
Example: Iterating Over a List
Output
Python Java C++
The range() Function¶
To iterate over a sequence of numbers, use the built-in range() function:
Syntax¶
start: Initial number (default 0).stop: Upper limit (exclusive; the sequence stops before this number).step: Increment value (default 1).
Example: Using range()
# 0 to 4
for i in range(5):
print(i, end=" ")
print()
# 2 to 10 with step 2
for n in range(2, 11, 2):
print(n, end=" ")
Output
0 1 2 3 4 2 4 6 8 10
Looping Helper Functions: enumerate() and zip()¶
1. enumerate(): Index and Value Together¶
When looping through a sequence and tracking index position, use enumerate():
frameworks = ["Django", "FastAPI", "Flask"]
for index, item in enumerate(frameworks, start=1):
print(f"{index}: {item}")
2. zip(): Multiple Sequences in Parallel¶
names = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
2. The while Loop¶
A while loop executes as long as a specified condition remains True.
Syntax¶
Example: Fibonacci Series using while
# Fibonacci series: the sum of two preceding numbers
a, b = 0, 1
while a < 50:
print(a, end=" ")
a, b = b, a + b
Output
0 1 1 2 3 5 8 13 21 34
Loop Control Statements: break, continue, and pass¶
break: Terminates the current loop execution immediately.continue: Skips the remainder of the current iteration and advances to the next iteration.pass: Does nothing. It is used as a syntactic placeholder.
Example: break and continue
The else Clause on Loops¶
In Python, loops can have an else clause. The else block executes only if the loop completes without encountering a break statement: