Essential Guide to Loops and Recursion in Python

Filipe Filardi
6 min readDec 28, 2022

--

Image by Clément Hélardot

Welcome back to my introduction to Python written course! The previous article covered comparison operators, logical operators, and conditional statements to create branching logic.

Loops are essential in programming, as they allow us to repeat a particular block of code multiple times. In Python, we have two types of loops: for loops and while loops. This article will explore how to use both of these loops in Python.

Assignment Operators

Assignment operators are used to assigning a value to a variable in Python. The most basic assignment operator is the equal sign (=), which is used to assign a value to a variable. For example:

x = 10  # This will assign the value 10 to the variable x 

Compound assignments operators

It is essential to talk about compound assignment operators before discussing loops because they can be used in the condition of a while loop to update the value of a variable.

Compound assignment operators allow us to perform an operation and assign the result to a variable in a single step. For example:

x = 10
x += 5 # This will add 5 to x and assign the result (15) to x

Without compound assignment operators, we might need to use a separate assignment statement, which can make the code more verbose and less readable. For example:

x = 10
x = x + 5 # The same resutl as the example above

There are several compound assignment operators in Python, including +=, -=, *=, /=, and %=. Here are some examples of using them:

x = 10
y = 5
z = 2

x += y # x is now 15
x -= z # x is now 13
x *= y # x is now 65
x /= z # x is now 32.5
x %= y # x is now 2.5

There are many other compound assignment operators, but since they’re not used for general purposes, I won’t cover them in this article.

“While” Loops

A while loop in Python allows us to repeat a particular code block as long as a specific condition is met. Here is the basic syntax for a while loop in Python:

while condition:
# code to be executed

Let’s see an example of a while loop in action. Suppose we want to print the numbers from 1 to 5 to the console:

i = 1
while i <= 5:
print(i)
i += 1

This will output the following to the console:

1
2
3
4
5

It’s important to note that we need to specify a way to update the value of i to avoid an infinite loop.

“For” Loops

A for loop in Python allows us to iterate over a sequence of elements, such as a list or a string. Here is the basic syntax for a for loop in Python:

for element in sequence:
# code to be executed

Let’s see an example of a for loop in action. Suppose we have a list of integers, and we want to print each of them to the console:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)

This will output the following to the console:

1
2
3
4
5

We can also use a for loop to iterate over a string. For example:

name = "Phil"
for letter in name:
print(letter)

This will output the following to the console:

P
h
i
l

Another useful feature of for loops are the ability to use the range() function to specify the number of iterations. The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (also by default), and stops before a specified number. For example:

for i in range(5):
print(i)

This will output the following to the console:

0
1
2
3
4

We can also specify the start and stop values for the range() function. For example:

for i in range(2, 5):
print(i)

This will output the following to the console:

2
3
4

Finally, we can also specify the step size for the range() function. For example:

for i in range(1, 10, 2):
print(i)

This will output the following to the console:

1
3
5
7
9

When to Use Which Loop?

In general, for loops are better suited for situations where we need to iterate over a known sequence of elements, such as a list or a string. While loops are better suited for situations where we need to repeat a particular task until a specific condition is met, such as when reading input from the user or waiting for a network connection to be established.

However, it is possible to use either type of loop in most general uses to solve most problems. In these cases, it’s a good idea to consider which type of loop will be more readable and maintainable for the task at hand.

Recursion

Recursion is a programming technique in which a function calls itself to repeat a specific task. This can be a useful way to solve particular problems, as it allows us to break a problem down into smaller, more manageable pieces that can be solved independently.

Here is a simple example of a recursive function:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

This function calculates the factorial of a number, which is the product of all the positive integers from 1 to n. It uses a base case (if n == 1) to stop the recursion when we reach the end of the sequence.

If the value of n is 1, the function returns 1. Otherwise, the function calls itself with a value of n - 1, and multiplies the result by n. This allows us to break down the factorial calculation into smaller pieces that can be solved independently.

We can call this function like this:

print(factorial(5))  # Outputs 120

Recursion can be a powerful tool for solving problems, but it can also be risky if not used carefully. In particular, it’s essential to include a base case to stop the recursion, or else the function may continue to call itself indefinitely and create an infinite loop.

It’s also important to consider the performance of a recursive solution, as it may be slower and use more memory than an iterative solution. In some cases, it may be more efficient to use an iterative approach, such as a for loop to solve a problem.

Here is an example of the solution using a for loop:

def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

The recursive version breaks down the calculation into smaller pieces that are solved independently, while the iterative version performs the calculation all at once.

There are differences in performance and efficiency. The recursive version may be slower and use more memory due to the overhead of repeatedly calling the function. The iterative version may be faster and use less memory, as it performs the calculation all at once and does not require the overhead of function calls.

Generally, it’s essential to consider the trade-offs between recursive and iterative.

In conclusion, loops are a fundamental programming concept that allows us to repeat a code block multiple times. In Python, we have two types of loops, while loops, and for loops.

Also, recursion is a programming technique in which a function calls itself to repeat a task. This can be a valuable way to solve specific problems. It’s essential to include a base case to stop the recursion and consider the performance and efficiency of the solution.

The following article dives deep into Python strings.

Stay tuned, and let’s code!

If you’re interested in reading other articles written by me. Check out my repo with all articles I’ve written so far, separated by categories.

Thanks for reading

--

--

Filipe Filardi

Data Scientist with a passion for making Development and Data Science more accessible