For AI agents: use /llms.txt for the Nakafa content index.
Python provides several special statements to control the execution flow in loops. These statements allow you to control when loops should stop, continue, or perform certain actions.
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 does nothing but is useful as a placeholder for code that hasn't been written yet. Python requires at least one statement in every code block.
# 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. This pattern is especially useful for searches: handle a match before break, and handle "not found" 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 listUse 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.
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.
The zip() function allows you to iterate over multiple iterables simultaneously. Think of it like a zipper that combines two sides into one.
# 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 it stops at the shortest iterable, which can hide a length mismatch; use zip(..., strict=True) when unequal lengths should be an error.
# 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'))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.
The range() function creates a sequence of numbers that can be iterated. This is very useful for loops with numeric indices.
# 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.
A range stores a compact start, stop, and step instead of materializing every integer. It computes values as they are 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
# More efficient - using range
for i in range(n): # Doesn't store all numbers in memory
if i < k:
print(i)
else:
breakConditional 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.
# 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.
# Determining quadrant from coordinate point
x = (-1, -3)
if 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 quadrantNested if is useful for making more complex decisions with multiple levels of conditions.
For loops in Python are used to iterate elements in iterable objects like lists, tuples, strings, or ranges.
# 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. The in operator performs type-specific membership testing, while colons and consistent indentation define statement blocks.