Loop Control Statements
Python provides several statements that change the flow of a loop. They can stop the loop, skip to the next iteration, or define what happens after normal completion.
Break Continue Pass and Else
The break statement exits the nearest enclosing loop immediately when a condition is met. Execution then continues with the first statement after that loop.
# Finding number divisible by 15 and 25
x = 0
while True:
x += 1
if not (x % 15 or x % 25):
break
print(x, 'is divisible by 15 and 25')
# Output: 75 is divisible by 15 and 25The continue statement skips the rest of the code in the current iteration and continues to the next iteration. This is different from break which stops the entire loop.
# Printing only even numbers
for i in range(1, 11):
if i % 2:
continue
print(i, 'is even.')
# Output:
# 2 is even.
# 4 is even.
# 6 is even.
# 8 is even.
# 10 is even.The pass statement performs no action. It keeps an otherwise empty block syntactically valid while its implementation is still pending.
# pass is a no-op. It does not skip the iteration
for i in range(1, 11):
if i == 6:
pass # Do nothing for number 6
if not i % 3:
print(i, 'is divisible by 3')
# Output:
# 3 is divisible by 3
# 6 is divisible by 3
# 9 is divisible by 3The else block runs when the loop finishes without executing break. In a search loop, handle a match before break and handle the "not found" case in else.
# Searching for negative numbers in list
numbers = [0, 4, 2, 5]
for i in numbers:
if i < 0:
break
else:
print('no negative number in list')
# Output: no negative number in listEnumerate Function
Use enumerate() when an iteration needs both a counter and each value. It returns an iterator that yields (index, value) tuples.
# Using enumerate to get index and value
fruits = ['apple', 'banana', 'mango', 'melon']
for i, fruit in enumerate(fruits):
print(i, ':', fruit)
# Output:
# 0 : apple
# 1 : banana
# 2 : mango
# 3 : melonBy default, enumerate() starts counting from , but you can set the starting value with the second parameter.
# Setting custom start index for enumerate
fruits = ['apple', 'banana', 'mango', 'melon']
for i, fruit in enumerate(fruits, 5):
print(i, ':', fruit)
# Output:
# 5 : apple
# 6 : banana
# 7 : mango
# 8 : melonIn for i, fruit in enumerate(fruits), tuple unpacking binds the index to i and the corresponding value to fruit on every iteration.
While Loop
The while loop executes a block as long as its condition is truthy. A for loop consumes an iterable, while a while loop repeats from a condition that the body usually updates.
# Example while loop with mathematical calculation
z = 1
while abs(z) < 100:
z = z**2 + 1
print(z)
# Output: 677A while loop fits condition-driven repetition, but its body must eventually change the condition or explicitly exit. Otherwise the loop can run forever.
Zip Function
The zip() function pairs items at the same position in several iterables. Iteration stops when the shortest iterable runs out of items, so the number of pairs equals the length of the shortest input.
Basic Zip Usage
# Combining two lists with zip
p = [1, 2, 3, 4]
q = ['a', 'b', 'c', 'd']
for pair in zip(p, q):
print(pair)
# Output:
# (1, 'a')
# (2, 'b')
# (3, 'c')
# (4, 'd')The zip() function returns an iterator of tuples. Each tuple contains corresponding elements from the inputs. By default, iteration stops when the shortest iterable ends, so remaining elements in longer inputs are omitted. Use zip(..., strict=True) to raise an error when the input lengths differ.
Converting Zip Results
You can read pairs from a zip() iterator directly in a loop. Convert it to a list or tuple when you need to retain those pairs for reuse.
# Converting zip results to list or tuple
p = [1, 2, 3, 4]
q = ['a', 'b', 'c', 'd']
zipped = zip(p, q)
print(list(zipped)) # Convert to list
# Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
# Zip object already consumed, create new one
zipped_new = zip(p, q)
print(tuple(zipped_new)) # Convert to tuple
# Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))Unzipping with the Asterisk Operator
The unpacking operator * can separate a nonempty collection of zipped tuples by position.
# Separating data that has been zipped
pairs = [(1, 'a'), (2, 'b'), (3, 'd')]
numbers, letters = zip(*pairs)
print(numbers, letters)
# Output: (1, 2, 3) ('a', 'b', 'd')This process is called "unzipping" because it separates data that has been combined.
Range and For Loop
The range() function produces a sequence of integers for iteration. Use it when a loop needs numeric positions or a fixed number of repetitions. Because range yields each value on demand instead of storing the whole sequence, its memory use stays small even when the loop runs millions of times.
Range Syntax
# Various ways to use range
# range(stop) - from 0 to stop-1
for i in range(4):
print(i)
# Output:
# 0
# 1
# 2
# 3
print()
# range(start, stop) - from start to stop-1
for i in range(2, 6):
print(i)
# Output:
# 2
# 3
# 4
# 5
print()
# range(start, stop, step) - with specific step
for i in range(8, 4, -1):
print(i)
# Output:
# 8
# 7
# 6
# 5Range follows an arithmetic formula where each i-th element is start + i * step for all i from to n-1.
Range vs List Efficiency
A range stores only its start, stop, and step. It computes each integer when requested, so its memory use does not grow with the number of represented integers.
# Comparing range vs list efficiency
n = 10000
k = 10
# Materializes every integer in memory
index = list(range(n))
for i in index:
if i < k:
print(i)
else:
break
# Uses range without building a list
for i in range(n): # Doesn't store all numbers in memory
if i < k:
print(i)
else:
breakConditional Statements
Conditional statements let a program choose a branch from evaluated conditions. Indentation is part of Python's syntax. Use four spaces per level and never mix tabs and spaces in one block.
If Elif and Else Syntax
# Complete if/elif/else structure
age = 20
if age <= 5:
print("free entrance")
elif age <= 14:
print("15.00 EUR")
elif age <= 65:
print("30.00 EUR")
else:
print("20.00 EUR")
# Output: 30.00 EURConditions do not need surrounding parentheses, and the colon after each branch header is required. Every statement in one block must use a consistent indentation level.
Nested If Statement
# Determining quadrant from coordinate point
x = (-1, -3)
if x[0] == 0 or x[1] == 0:
print('on a coordinate axis')
elif x[0] > 0:
if x[1] > 0:
print('first quadrant')
else:
print('fourth quadrant')
elif x[1] > 0:
print('second quadrant')
else:
print('third quadrant')
# Output: third quadrantUse nested decisions when the selected branch determines which condition to check next. Checking for zero coordinates first prevents points on an axis from being assigned to a quadrant.
For Loop Syntax
A for loop visits the elements of an iterable such as a list, tuple, string, or range.
# Example list iteration
fruit_list = ['apple', 'banana', 'mango']
for fruit in fruit_list:
print(fruit)
# Output:
# apple
# banana
# mango
# Example string iteration
text = 'hi'
for char in text:
print(char)
# Output:
# h
# iAn iterable supplies values one at a time, but it is not necessarily ordered, indexable, reusable, or finite. A for loop asks its iterator for successive values. In a for header, in connects the iteration target to the iterable. In an expression such as 3 in [1, 3], in tests membership.