Python iterations and basic algorithms
In this lesson you will learn how to use iterations (repetition) to solve simple algorithmic problems. Iterations are one of the most important concepts in programming and let you repeat a part of the code several times, most often with the for and while loops.
1. What is an iteration?
Iteration means repetition. Computers are very good at repeating the same operations at great speed, so iterations are used for:
- adding up a series of numbers
- finding the minimum/maximum
- counting elements
- searching a list
- going through a text or a sequence of characters
2. Iterating through a range of numbers
The most common way of iterating in Python is using the function range():
for i in range(1, 6):
print(i)
This program prints the numbers from 1 to 5.
In the function range(a, b) the starting value is a, and the last one is b - 1.
3. Adding numbers — a basic algorithm
One of the first algorithms programmers learn is adding the first n numbers:
n = 5
total = 0
for i in range(1, n + 1):
total += i
print("The sum is:", total)
This algorithm starts from zero and adds all the numbers from 1 to n.
4. Finding the maximum
An algorithm for finding the biggest number in a list:
numbers = [3, 8, 2, 11, 5]
maximum = numbers[0]
for number in numbers:
if number > maximum:
maximum = number
print("The biggest number is:", maximum)
5. Counting elements
An example of an algorithm that counts how many even numbers there are in a list:
numbers = [1, 2, 4, 7, 10, 13]
count = 0
for x in numbers:
if x % 2 == 0:
count += 1
print("Number of even numbers:", count)
6. Mini tasks — iterations and algorithms
- Write a program that adds up all the even numbers from 1 to 100
- Calculate the product of all the numbers from 1 to n
- Find the smallest number in a list entered from the keyboard
- Count how many times the letter "a" appears in an entered text
- Check whether a certain number is in a list
This lesson prepares you for more complex algorithmic tasks used in programming, robotics and artificial intelligence.
Nested loops
Nested loops are loops that are inside other loops. This means that one loop (the inner one) runs several times during one pass of the other loop (the outer one).
This is very common in programming and is used when we:
- work with tables and matrices
- compare every element with every other element
- draw patterns (rectangles, triangles)
- develop basic algorithms
How do nested loops run?
First the outer loop runs. For each of its passes, the inner loop runs completely.
We can imagine the order like this:
Outer loop → pass 1
Inner loop → all passes
Outer loop → pass 2
Inner loop → all passes
...
That is why the inner code often runs many times, which is important for understanding algorithms.
A small visual example of the flow
for i in range(3):
for j in range(2):
print("i =", i, "j =", j)
Here:
- the outer loop (
i) goes from 0 to 2 - for each
i, the inner loop (j) goes from 0 to 1
In total print runs 3 × 2 = 6 times.
Short practical examples
Example 1: Printing coordinates
for x in range(1, 4):
for y in range(1, 3):
print("(", x, ",", y, ")")
This example shows all the possible pairs of values
x and y.
It is used in games, mathematics and working with grids.
Example 2: A rectangle of stars
for i in range(3):
for j in range(5):
print("*", end="")
print()
The outer loop decides the number of rows, and the inner loop the number of columns. The result is a rectangle 5 wide and 3 high.
Examples of nested loops (basic algorithms)
The following examples show typical situations in which nested loops are used. The examples are short and focus on understanding how they run.
Example 1: A small multiplication table
Task:
Write a program that prints the multiplication table for the numbers from 1 to 3.
Input:
There is no user input.
Output:
1 2 3 2 4 6 3 6 9
Explaining the algorithm
The outer loop goes through the rows of the table (the numbers 1–3), while the inner loop goes through the columns. For each pair of numbers their product is calculated.
Solution
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()
Explaining the solution
iis the rowjis the columnend=" "prevents moving to a new lineprint()at the end of a row starts a new line
Visualising the flow (example)
i = 1 → j = 1, 2, 3 → 1 2 3 i = 2 → j = 1, 2, 3 → 2 4 6 i = 3 → j = 1, 2, 3 → 3 6 9
Example 2: Printing coordinates (i, j)
Task:
Print all the pairs of coordinates (i, j) where i goes from 1 to 3,
and j from 1 to 2.
Input:
There is no user input.
Output:
(1, 1) (1, 2) (2, 1) (2, 2) (3, 1) (3, 2)
Explaining the algorithm
For each value of the variable i,
the inner loop goes through all the values of j
and prints the pair.
Solution
for i in range(1, 4):
for j in range(1, 3):
print(f"({i}, {j})")
Explaining the solution
The outer loop controls the first coordinate, and the inner loop the second. In this way we get all possible pairs.
Example 3: A simple square of stars
Task:
Write a program that prints a 4×4 square of the character *.
Input:
There is no user input.
Output:
**** **** **** ****
Explaining the algorithm
The outer loop decides the number of rows, while the inner loop decides the number of stars in each row.
Solution
for i in range(4):
for j in range(4):
print("*", end="")
print()
Explaining the solution
The inner loop prints four stars in the same row,
and the empty print() moves to a new line.
Iteration patterns – basic algorithmic tools
In programming certain ways of using loops keep coming back. We call these repeating techniques iteration patterns. Understanding them is key to solving algorithmic problems.
1. Counting forwards and backwards
Task:
Print the numbers from 1 to 5 forwards, and then from 5 to 1 backwards.
Input:
There is no user input.
Output:
1 2 3 4 5 5 4 3 2 1
Explaining the algorithm
For counting forwards we use an increasing range, while for counting backwards we use a range with a negative step.
Solution
for i in range(1, 6):
print(i, end=" ")
print()
for i in range(5, 0, -1):
print(i, end=" ")
Explaining the solution
The function range() lets you control the start,
the end and the direction of the numbers.
2. The accumulator – adding and counting
Task:
Calculate the sum of the numbers from 1 to 5 and count how many there are.
Output:
Sum: 15 Number of elements: 5
Explaining the algorithm
An accumulator is a variable that keeps a result which changes step by step as we go through the loop.
Solution
total = 0
count = 0
for i in range(1, 6):
total += i
count += 1
print("Sum:", total)
print("Number of elements:", count)
Explaining the solution
totalaccumulates the sum of the numberscountcounts how many times the loop has run
3. Finding the maximum and the minimum
Task:
Find the biggest and the smallest value in a list of numbers.
Input:
numbers = [3, 7, 2, 9, 4]
Output:
Maximum: 9 Minimum: 2
Explaining the algorithm
At the start we assume that the first element is both the maximum and the minimum, and then we update them when needed.
Solution
numbers = [3, 7, 2, 9, 4]
max_value = numbers[0]
min_value = numbers[0] # we do not call it min – that is the name of a built-in Python function
for number in numbers:
if number > max_value:
max_value = number
if number < min_value:
min_value = number
print("Maximum:", max_value)
print("Minimum:", min_value)
Explaining the solution
Every element is compared with the current maximum and minimum, which solves the problem in one pass through the list.
4. Stopping when found (break as an algorithmic tool)
Task:
Find the first number greater than 10 in a list of numbers and stop the loop.
Input:
numbers = [4, 7, 12, 5, 20]
Output:
Found number: 12
Explaining the algorithm
As soon as the value we are looking for is found,
there is no need to continue the loop.
At that moment we use break.
Solution
numbers = [4, 7, 12, 5, 20]
for number in numbers:
if number > 10:
print("Found number:", number)
break
Explaining the solution
The command break stops the loop right after the element
we are looking for is found, which makes the algorithm more efficient.
The link between loops and algorithms
When we talk about algorithms, it is important to understand how many times a certain part of the code runs. With an ordinary loop, some code repeats as many times as there are elements or steps. However, with nested loops, the inner code runs for each pass of the outer loop, which means that the total number of runs grows quickly. That is why algorithms with nested loops become "slower" as the amount of data grows.
Look at the following example:
for i in range(3):
for j in range(3):
print("Working")
In this case the message "Working" is printed
9 times, because the inner loop runs
three times for each of the three passes of the outer loop.
With one loop the number of runs grows gradually,
while with nested loops it grows much faster.
Hidden mini quiz — iterations and basic algorithms
Click to check whether you understand how
nested loops and iteration patterns work, and
how break affects the flow of an algorithm.
Open the quiz
Mini quiz: understanding iterations
1. How many times will the message be printed?
for i in range(3):
for j in range(2):
print("Python")
2. What is the role of the outer loop in nested loops?
3. What is an accumulator in an algorithm?
4. What will be printed?
for i in range(1, 6):
if i == 3:
break
print(i)
5. Why can algorithms with nested loops be slower?
Recommended practice tasks
To strengthen the material about iterations and basic algorithms, extra practice with tasks that develop algorithmic thinking is recommended. Below are suggested types of tasks and extra resources.
Tasks for independent work (Python)
- Calculate the sum of the numbers from 1 to n with a loop
- Find the biggest and the smallest number in a list
- Count how many positive numbers, negative numbers and zeros there are in a sequence of numbers
- Calculate the product of the elements of a list
- Count how many numbers are even and how many are odd
These tasks use the same iterative patterns that are explained in this lesson and do not need any extra material.
Algorithmic tasks in other languages (C / C++)
Although the following examples are written in C/C++, their value is in the algorithmic logic, which applies completely in Python too. Students are recommended to:
- read the task
- understand the algorithm
- try to translate it into Python on their own
➡ Examples of loops in C/C++:
Loops in C/C++ – examples
➡ Examples of nested loops (more advanced):
Nested loops – examples in C++
Note:
Nested loops are a more advanced topic and are recommended only after
you fully understand basic iterations.
Back to the Python tutorial
If you want to see the whole structure of the Python tutorial and where this lesson is compared with the other topics, visit the starting page:
➡ Python – the basic tutorial (an overview of all the lessons)
