Control flow statements
for Loop: Introduction
• The for statement is used to iterate over a
sequence (list, tuple, string, range, etc.).
• It executes the block of code once for each
item in the sequence.
• Commonly used for counting, searching, and
processing collections.
for Loop: Basic Syntax
Syntax:
for item in sequence:
# body of loop
Example:
for i in range(5):
print(i) # prints 0 to 4
for Loop Over a List
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Iterates through each element of the list and
prints it.
Nested for Loops
You can use one for loop inside another.
Example:
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
Useful for working with matrices, grids, or
combinations.
break Statement: Introduction
• break is used to exit the nearest enclosing loop
immediately.
• Control moves to the first statement after the
loop.
• Often used when a required condition is met
early.
break with for Loop: Example
Example:
for i in range(10):
if i == 5:
break # exit the loop when i is 5
print(i)
Output: 0 1 2 3 4 (loop stops when i == 5)
Using break for Searching
Example:
numbers = [3, 8, 15, 23, 42]
target = 15
for n in numbers:
if n == target:
print('Found', target)
break
• Stops searching once the target is found.
continue Statement: Introduction
• continue skips the rest of the code inside the
loop for the current iteration.
• Control jumps to the next iteration of the loop.
• Useful for skipping specific values or
conditions.
continue with for Loop: Example
Example:
for i in range(6):
if i == 3:
continue # skip printing 3
print(i)
Output: 0 1 2 4 5 (3 is skipped)
continue in Filtering
Example:
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 != 0:
continue # skip odd numbers
print(n)
Prints only even numbers: 2 4 6
return Statement: Introduction
• return is used inside a function to send a value
back to the caller.
• It immediately exits the function.
• Code after return in the function body does not
execute.
return: Basic Example
Example:
def add(a, b):
result = a + b
return result
x = add(3, 5)
print(x) # Output: 8
return vs break vs continue
• break: exits the nearest loop only.
• continue: skips to the next loop iteration.
• return: exits the current function (and may
optionally return a value).
• return can indirectly exit loops if the loop is
inside a function.
Combining for, break, and continue
You can mix break and continue in the same loop.
Example:
for i in range(1, 10):
if i % 2 != 0:
continue # skip odd numbers
if i == 8:
break # stop at 8
print(i)
Output: 2 4 6