Back to articles list Articles
12 minutes read

10 Python Loop Practice Exercises for Beginners with Detailed Solutions

If you’re looking to learn Python, there are many resources available. A great way to increase your skills is to do practice exercises. This gives you hands-on experience in solving realistic problems. Here, we give you 10 exercises for practicing loops in Python.

Python is a versatile and beginner-friendly programming language that offers a wide array of tools and features to simplify the process of creating software applications. It’s a great language for beginners to learn, as we explain in Why Python Is the Perfect First Programming Language for Beginners.

One of the most fundamental aspects of Python is the concept of looping. Loops allow you to repeatedly execute a block of code, enabling you to automate repetitive tasks and iterate over data structures easily. Understanding loops is crucial for any aspiring Python programmer, as it unlocks the potential to write efficient, scalable, and concise programs.

In this article, we will explore ten practice exercises specifically designed to enhance beginners’ understanding of looping in Python. We’ll also provide you with detailed solutions. These exercises are taken directly from our online courses – mostly from the Python Data Structures in Practice course, but also from the Python Basics Part 1, Part 2, and Part 3 series. These courses are perfect for beginners wanting to learn the fundamentals of programming in Python. They include interactive exercises that start from the basics and work up to more challenging material. By attempting these exercises, you will gain invaluable hands-on experience. It will hone your skills in implementing loops effectively and solving common programming challenges.

To get the most benefit from this article, try to solve the problems before reading the solutions. Some of these exercises will have a few possible solutions, so also try to think about alternative ways to solve the same problem.

Let’s get started.

Exercise 1: Basic for Loop

Suppose you want to write a program that prints numbers from 1 to 10, formatted like this:

Current value: 1
Current value: 2
...
Current value: 10

How can you do that?

Solution

for i in range(1, 11):
    print('Current value:', i)

Here, we implement a basic for loop using the range() built-in function, which takes three arguments: start, stop, and step. We define start as 1 and stop as 11, and step takes the default value of 1. We use the print() function to print the results. Notice that the loop prints the values until 10 – that is, one less than the stop value.

Since you’ll be printing things all the time in Python, check out How to Print in Python – A Detailed Guide for Beginners. This function can do more than you think.

Exercise 2: Basic while Loop

Try the above exercise using a while loop. You’ll need to define a counter and an appropriate stopping condition. And you’ll need to manually increment the counter after every loop.

Solution

counter = 1
while counter <= 10:
    print('Current value:', counter)
    counter = counter + 1

The code initializes the variable counter with the value of 1. It then executes the code block inside the loop as long as the condition counter <= 10 remains true. Within each iteration, the current value is printed as in the first exercise. Afterward, the counter is incremented by 1, ensuring that it increases with each iteration of the loop. The loop continues executing until the condition evaluates to False.

Exercise 3: Nested Loops

Use nested loops to print the following output:

111111111
222222222
...
888888888
999999999

First, you will need a string variable where you will add the characters to be printed on the current line.
If your outer loop uses a variable named i, then your inner loop should use range(0, 9). In the inner loop, all you have to do is add the value of i to the string variable. You have to cast the integer i to a string first with str(i).

After the inner loop finishes, the outer loop prints the string variable and then sets it to the empty string '', clear for reuse in the next iteration.

Solution

line_to_print = ''
for i in range (1, 10):
    for j in range (0, 9):
        line_to_print += str(i)
    print(line_to_print)
    line_to_print = ''

This code constructs a string that contains a series of numbers. It starts by adding the value of i to the empty string line_to_print and then appends it repeatedly for each iteration of the nested loop. The outer loop over i defines the number to print; the inner loop over j defines the number of times to append the number to the string. Once the nested loop completes, line_to_print is reset back to an empty string and the outer loop begins its next iteration.

Exercise 4: Looping Over a List

You are given a list of countries. For each country in the list, print the following sentence:

{country} contains {len(country)} letters!

Use the following list:

countries = ['Thailand', 'Vietnam', 'Malaysia', 'UAE']

Solution

countries = ['Thailand', 'Vietnam', 'Malaysia', 'UAE']
for country in countries:
    print(country, 'contains', len(country), 'letters!')

The solution consists of a loop that iterates over each country in the list. During each iteration, the variable country stores the current country name. Inside the loop, a print() statement displays the name of the country, followed by the string 'contains' and the length of the country name. The len() built-in function returns the number of characters in the current country name. This process is repeated for all the countries in the list.

We have more list practice exercises in our article 12 Beginner-Level Python List Exercises with Solutions. Try them out for more practice – but for now, we’ll focus on working with some other Python data structures.

Exercise 5: Looping with a List of Tuples

Create a function named remove_sql_specialists(people_list). Given a list of tuples, it removes people whose job titles contain the word "SQL" from the list. You can use the in operator to check if a given job title contains the word "SQL". Use the following data containing employee names, job titles, and salaries:

new_hires = [('Mark Adams', 'SQL Analyst', 4000),
             ('Leslie Burton', 'HR Specialist', 2300),
             ('Dorothy Castillo', 'UX Designer', 3100)]

Solution

def remove_sql_specialists(people_list):
    for person in people_list[:]:
        if 'SQL' in person[1]:
            people_list.remove(person)

A tuple is another way to store data in Python. Lists are commonly used when you have a collection of elements and need to dynamically modify, add, or remove items. Tuples, on the other hand, are immutable and are often used when you have a collection of elements that shouldn't change, like coordinates or values that are unlikely to be modified. Since names, job titles, and salaries are unlikely to change, they are stored in a tuple. However, the data for each person is stored in a list, so employees can be easily added or removed.

In this solution, we iterate through a copy of the list. We explain why this is good practice in the Python Data Structures in Practice course. Using the in operator, we test if the string 'SQL' is in the second entry of the tuple using the index 1. If so, we remove it from the list.

Exercise 6: Looping Over Dictionaries

Use the iteration method you think is best for this exercise. Create a function named get_results_range(result_dict) that accepts the following dictionary and returns the difference between the best and worst exam results.

exam_results = {
'Dominic Vargas': 67,
'Marion Riley': 89,
'Candice White': 45,
'Doreen Goodwin': 82,
'Janet Hunter': 98,
'Jaime Page': 32,
'Neil Fernandez': 76,
'Jana Frank': 28,
'Adrienne Perkins': 98,
'Rosa Mccarthy': 34
}

Solution

def get_results_range(result_dict):
    max = 0
    min = 100
    for v in result_dict.values():
        if v > max:
            max = v
        if v < min:
            min = v
    return max – min

The function sets the variables max and min to 0 and 100, respectively. These variables are used to keep track of the maximum and minimum results found in the dictionary. The function enters a loop that iterates through each value in the dictionary using the values() method. For each value, the function compares it with the current maximum value; if the value is greater than the current maximum, it updates the variable max. Similarly, if the value is smaller than the current minimum value stored in the min variable, it updates the value of this variable.

After iterating through all the values in the dictionary, the function returns the difference between the maximum and minimum values.

Exercise 7: Counting Elements in Tuples and Dictionaries

You are given two data structures:

  • users – A list of forum users' names along with their nationalities (i.e. a list of tuples).
  • nationality_to_continents – A dictionary in which nationalities are keys and continents are values.

Create a dictionary named users_continents and use it to store the number of users for each continent in the following form:

users_continents = {'Europe': 3, 'Asia': 4, 'North America': 2}

Use the following data in your solution:

users = [
('Maria', 'Greek'), ('Jean', 'Maltese'),
('Juan', 'Spanish'), ('Dima', 'Ukrainian'),
('Agata', 'Thai'), ('Rafal', 'Polish'),
('Diego', 'Turkish'), ('Stan', 'Panamanian'),
('John', 'Australian'), ('Frank', 'Belgian'),
('Jane', 'Canadian'), ('Paul', 'Argentinian'),
('Taylor', 'Danish'), ('Kate', 'American'),
('Mark', 'Sri Lankan'), ('Jane', 'Japanese'),
('Ted', 'Indian'), ('Jean', 'Egyptian') 
]

nationality_to_continents = {
'Greek': 'Europe', 'Maltese': 'Europe', 
'Spanish': 'Europe', 'Ukrainian': 'Europe', 
'Thai': 'Asia', 'Polish': 'Europe', 
'Turkish': 'Asia', 'Panamanian': 'Central America', 
'Australian': 'Australia', 'Belgian': 'Europe', 
'Canadian': 'North America', 'Argentinian': 'South America', 
'Danish': 'Europe', 'American': 'North America', 
'Sri Lankan': 'Asia', 'Japanese': 'Asia', 
'Indian': 'Asia', 'Egyptian': 'Africa'
}

Solution

users_continents = {}
for user in users:
    _, nationality = user
    if nationality_to_continents[nationality] not in users_continents:
        users_continents[nationality_to_continents[nationality]] = 0
    users_continents[nationality_to_continents[nationality]] += 1

The solution starts by defining an empty dictionary to store our results in. Then there is a for loop over the users list, where each tuple is iteratively assigned to the user variable. The tuples consist of two elements: a name and a nationality. Since we’re only interested in the nationality, we skip the name element by using the underscore (_). The nationality of the user is assigned to the nationality variable.

We test if the nationality is not in the users_continents dictionary. If so, we set the value of that key to zero. The keys here are the continents and the values are the counts. Then, after the if statement, we continue the loop and increment the count for each continent that the users come from.

Exercise 8: Iterating with Sets

We want to manufacture key rings with the car makes found in the people_cars dictionary below. The size of each key ring will depend on the number of letters in the car make name. Create the set named car_make_lengths and add all unique car make length values to it. Then, print the following sentence:

There will be {x} different sizes of key rings.

Here is the dictionary:

people_cars = {'Adam': 'Volvo', 'Kate': 'BMW', 'Mark': 'BMW', 'Hannah': 'Ford', 'Max': 'Volvo', 'Celine':'Fiat'}

Solution

car_make_lengths = set()
for item in people_cars.values():
    car_make_lengths.add(len(item))
print('There will be', len(car_make_lengths), 'different sizes of key rings.')

Here we introduce a new data structure – a set. We’ve seen lists before, which are collections of mutable items that can contain duplicate values. We also worked with tuples, which are similar to lists but immutable, meaning they cannot be modified after creation. Sets, on the other hand, are collections of unique items, where duplicates are automatically removed.

This solution starts by defining the empty set car_make_lengths. Then we loop through the values in the people_cars dictionary. Since dictionaries store data in key-value pairs, the values are the car makes. Using the add() method, we add the length of the car make to the set. Notice that the ‘Ford’ and ‘Fiat’ values both have 4 letters. Using sets automatically removes duplicates, so we end up with only one value of 4 in the set.

Exercise 9: Create a Chess Bot

Create a function named next_position(current_position, move) that returns the position of the pawn after making a move. The current_position is a tuple representing the position of the pawn before making a move, i.e. (0, 2). The move is a string representing the move direction ('down', 'up', 'right', or 'left').

The result of next_position((0, 2), 'down') should be (0, 1).

Solution

def next_position(current_position, move):
    x, y = current_position
    if move == 'left':
        new_position = (x - 1, y)
    elif move == 'right': 
        new_position = (x + 1, y)
    elif move == 'up':
        new_position = (x, y + 1)
    else:
        new_position = (x, y - 1)
    return new_position

Although we don’t need any loops here, we will build off this solution in the last exercise of this article. This solution consists of using an if-elif-else statement to define a new position based on the move being either left, right, up, or down.

Exercise 10: Move Over, Deep Blue

Create a function called repeated_position(current_position, moves). For a given position (current_position) and list of moves (moves), it returns the first position in which the pawn finds itself for the second time (if such a position exists), or -1 if all positions occupied by the pawn are different. You can use the function next_position(current_position, move) that was created in the previous exercise.

To test your function, run it with the following inputs:

>>> print(repeated_position((2, 0), ["up", "left", "up", "left", "down", "right", "up", "right", "up", "left"]))

This gives the following output:

(1, 1)

Solution

def repeated_position(current_position, moves):
    positions = set()
    positions.add(current_position)
    for move in moves:
        new_position = next_position(current_position, move)
        if new_position in positions:
            return new_position
        else:
            positions.add(new_position)
            current_position = new_position
    return -1

We start by defining a set that will store all positions, starting with the current_position from the input. Then we simply loop through the list of moves and calculate the next position using the function from the previous exercise. If the next position is already in the positions set, we return the position. If not, we add it to the set and update the current position.

Sets in Python are a powerful tool. For some more information and examples of how they work, see the article Python Set Examples: From Basic to Advanced Use Cases.

Looking for More Python Loop Exercises?

Learning Python is an exciting journey that empowers you to create and explore endless possibilities in programming. Through this article, we have provided a range of practice exercises designed to improve your understanding of looping in Python. The exercises are taken directly from several of our online courses, including Python Basics Practice and Python Data Structures in Practice, both of which contain many more interactive exercises.

There are many Different Ways to Practice Python. For those of you who like getting a strong theoretical background, we have some recommendations for The 5 Best Python Books for Beginners.

Completing exercises is a great way to develop skills at solving a variety of problems. For some more hands-on learning material, take a look at our article  10 Python Practice Exercises for Beginners with Detailed Solutions. For more tips on learning effectively, see our article What’s the Best Way to Practice Python?. Happy coding!