Skip to content

Practical Exercises for Learning Loops in Python

Updated: at 04:23 AM

Loops are a fundamental concept in programming that allow you to repeatedly execute blocks of code in an efficient manner. Mastering loops is essential for automating repetitive tasks, iterating through sequences, and developing complex programs in Python. This comprehensive guide provides practical loop exercises for Python beginners to gain proficiency with for loops, while loops, nested loops, and more.

Table of Contents

Open Table of Contents

Introduction

Loops execute a block of code multiple times, allowing you to shorten and simplify your code. Instead of rewriting the same code, you can use a loop to cycle through values, iterate through sequences, or repeat tasks until a condition is met.

There are two main types of loops in Python:

Understanding how to construct and nest loops is critical for Python programmers. Loops are used in many real-world applications and common programming tasks:

This guide will provide step-by-step instructions for loop exercises covering these practical use cases. The hands-on examples use simple loops to demonstrate core concepts that can be applied to more advanced scenarios. Let’s begin!

For Loop Exercises

For loops execute code a predetermined number of times. The loop variable iterates over a sequence or range to repeat the enclosed block.

Looping Through a List

This exercise iterates through a list using a for loop to print each element:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
  print(fruit)

Output:

apple
banana
cherry

Sum Values in a List

Calculate the total of a list of numbers:

numbers = [1, 2, 3, 4, 5]

total = 0
for num in numbers:
  total += num

print(total)

Output:

15

Looping Through a String

Iterate through a string letter by letter using a for loop:

name = "John"

for letter in name:
  print(letter)

Output:

J
o
h
n

Looping Through Tuples and Dictionaries

For loops can iterate through tuples, dictionaries, and other sequence types:

colors = ("red", "green", "blue")

for color in colors:
  print(color)
person = {"name": "John", "age": 25, "job": "Analyst"}

for key in person:
  print(key, ":", person[key])

These examples demonstrate how for loops work consistently across different sequence data types in Python.

Looping Through Ranges

Generate a sequence of numbers using Python’s range() function:

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

To iterate from a start number to end:

for i in range(3, 8):
  print(i)

Output:

3
4
5
6
7

You can also define a step size:

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

Output:

1
3
5
7
9

These exercises demonstrate how to construct ranges for iteration in for loops.

While Loop Exercises

While loops repeat code as long as a condition remains true. The loop exits when the condition evaluates to false.

Loop with a Counter

Increment a counter from 1 to 5:

count = 1

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

Output:

1
2
3
4
5

Loop with a Break

Exit loop early by calling break:

numbers = [1, 2, 3, 4, 5]

i = 0
while i < len(numbers):
  if numbers[i] == 3:
    break
  print(numbers[i])
  i += 1

Output:

1
2

This demonstrates how to use break for early termination.

Loop with a Continue

Skip iteration with continue:

for i in range(10):
  if i % 2 == 0:
    continue
  print(i)

Output:

1
3
5
7
9

This example shows how to use continue to filter out values in a loop.

Nested Loop Exercises

Nesting loops allows you to loop through multidimensional sequences like grids, matrices, or nested lists.

Nested For Loop

Print rows and columns from a 2D list:

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

for row in matrix:
  for col in row:
    print(col)

Output:

1
2
3
4
5
6
7
8
9

Nested While Loop

Nested while loops to print a pattern:

i = 1
while i <= 3:
  j = 1
  while j <= 3:
    print(i, end=" ")
    j += 1
  print()
  i += 1

Output:

1 1 1
2 2 2
3 3 3

This demonstrates how while loops can also be nested in Python.

Loop Exercises Summary

These practical exercises covered common loop constructs and scenarios in Python:

You can expand on these examples to solve real-world problems requiring repetitive tasks. As you program in Python, try applying these loop techniques to process and analyze data, automate workflows, implement algorithms and more.

Mastering loops is a key skill on the path to becoming an effective Python coder. These hands-on exercises help you gain confidence for tackling more complex looping challenges.

Additional Exercises

Here are some additional loop exercises for further practice:

Prime Number Generator

Use a loop to print all prime numbers under 100:

for num in range(2, 100):
  for i in range(2, num):
    if (num % i) == 0:
      break
  else:
    print(num)

Fibonacci Sequence

Print the Fibonacci sequence up to n terms:

n = 10

a, b = 0, 1
for i in range(n):
  print(a)
  a, b = b, a + b

File Reading/Writing Loops

Read a file line by line and write output to another file:

with open('file1.txt') as f:
  with open('file2.txt', 'w') as f2:
    for line in f:
      f2.write(line)

Data Analysis/Pandas Loops

Loop through rows in a Pandas DataFrame and process data:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

for index, row in df.iterrows():
  # process row data
  print(row['A'], row['B'])

These are just a few examples of more advanced loops for practice. Continue exploring and applying loops to build your Python skills.

Conclusion

This guide covered a collection of hands-on loop exercises in Python, starting from basics to more complex nested loops. Mastering loops is essential to level up your Python programming abilities for real-world tasks.

These examples should provide you with a solid foundation getting started with loops. Try experimenting with the code examples to deepen your understanding. Extend them for your own practice scenarios to become proficient using loops.

Remember to also leverage Python’s extensive libraries when suitable rather than reinventing the wheel writing complex looping logic. Many data types like lists and dictionaries have built-in functions that handle iterations internally.

With diligent practice, loops will become second nature in your Python code. You’ll be able to use them efficiently as part of your core toolset for building robust programs and scripts.