Introduction to loops in Python

Jeeshan
“Grokking Python Fundamentals”
12 min readJul 24, 2024
Photo by Mohammad Rahmani on Unsplash

Loops are fundamental programming structures that allow repetitive execution of a block of code while certain conditions are met. They are incredibly useful for tasks that require the same action or a similar set of actions to be performed multiple times, which is a common scenario in programming. Python provides several loop constructs that enable these repetitive actions to be handled in an efficient, readable, and concise manner.

Types of Loops and Control Statements

  1. for Loop: Used for iterating over a sequence (such as a list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
  2. while Loop: Repeats as long as a certain boolean condition is met. It is useful when the number of iterations is not known before the first iteration begins.
  3. Loop Control Statements: Modify the behavior of the loop from its normal sequence. These are:
  • break: Exits the loop immediately, skipping the remainder of its body and any remaining iterations.
  • continue: Skips the rest of the loop’s body for the current iteration and moves on to the next iteration of the loop.
  • pass: Acts as a placeholder; it does nothing and is used when a statement is required syntactically but no action needs to be performed.

Loops can significantly reduce the amount of code required in a program by handling repetitive tasks automatically while making the code easier to read and maintain. They are a powerful tool in data processing, automating tasks, and more. Understanding how to use loops efficiently is a crucial skill in programming.

In the following lessons, we will dive deeper into each type of loop and control statement, exploring their syntaxes, use cases, and best practices. Let’s start with the for loop in Python.

Photo by alban on Unsplash

Syntax of the for Loop

The basic syntax of a for loop in Python is as follows:

# Define a list of two lists, each with numbers
matrix = [[1, 2, 3], [4, 5, 6]]

# Outer loop to iterate over each list in the matrix
for row in matrix:
# Inner loop to iterate over each number in the list
for num in row:
print(num)
print() # prints a newline after each row

Explanation:

  • iterable: This is the collection of elements that the loop will iterate over. It can be a list, a tuple, a dictionary, a set, or any object that supports iteration.
  • variable: For each iteration of the loop, the variable takes on the value of the next element in the iterable.

Basic Example

Let’s look at a simple example to understand the basic functionality of the for loop.

# Define a list of two lists, each with numbers
matrix = [[1, 2, 3], [4, 5, 6]]

# Outer loop to iterate over each list in the matrix
for row in matrix:
# Inner loop to iterate over each number in the list
for num in row:
print(num)
print() # prints a newline after each row

Explanation:

  • fruits = ['apple', 'banana', 'cherry']: Defines a list of fruits.
  • for fruit in fruits:: Starts a loop over the fruits list. With each iteration, the variable fruit will take the value of one item from the list.
  • print(fruit): Executes for each iteration of the loop, printing the current value of fruit.

This example demonstrates how to use a for loop to iterate over a list and perform an action with each element, which in this case is printing the element. This approach is clear and concise, avoiding the need for indexing and the associated risks of off-by-one errors or boundary issues.

Looping Through Dictionaries

Dictionaries in Python are key-value pairs. You can iterate over them in several ways, depending on whether you need access to keys, values, or both.

# Define a list of two lists, each with numbers
matrix = [[1, 2, 3], [4, 5, 6]]

# Outer loop to iterate over each list in the matrix
for row in matrix:
# Inner loop to iterate over each number in the list
for num in row:
print(num)
print() # prints a newline after each row

Explanation:

  • info = {'name': 'John', 'age': 30, 'city': 'New York'}: Initializes a dictionary with three key-value pairs.
  • for key in info:: Iterates over each key in the dictionary by default. If you need to iterate over values or key-value pairs, you could use info.values() or info.items(), respectively.
  • print(key, "->", info[key]): Prints each key and its corresponding value. To directly access both key and value in the loop, use for key, value in info.items():

Nested Loops

A nested loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”.

# Define a list of two lists, each with numbers
matrix = [[1, 2, 3], [4, 5, 6]]

# Outer loop to iterate over each list in the matrix
for row in matrix:
# Inner loop to iterate over each number in the list
for num in row:
print(num)
print() # prints a newline after each row

Explanation:

  • matrix = [[1, 2, 3], [4, 5, 6]]: Sets up a list containing two lists, each with three integers.
  • for row in matrix:: The outer loop iterates over each sublist in matrix.
  • for num in row:: The inner loop iterates over each element in the current sublist referred to by row.
  • print(num, end=' '): Prints each number followed by a space instead of the default newline.
  • print(): After the inner loop completes for a sublist, it prints a newline to separate the rows visually.

Using the range() Function with Loops

The range() function in Python is frequently used with for loops to generate sequences of numbers. This function is extremely versatile and beneficial when you need to execute a loop a specific number of times. The range() function can be used in several ways depending on the parameters provided:

  1. Single parameter: Generates a sequence from 0 up to, but not including, the specified number.
  2. Two parameters: Generates a sequence from the first parameter to the second parameter, not including the second parameter.
  3. Three parameters: The third parameter specifies the step, or increment, between each number in the sequence.
# Define a list of two lists, each with numbers
matrix = [[1, 2, 3], [4, 5, 6]]

# Outer loop to iterate over each list in the matrix
for row in matrix:
# Inner loop to iterate over each number in the list
for num in row:
print(num)
print() # prints a newline after each row

Explanation:

  • for i in range(10):: Iterates over numbers 0 through 9. It uses range(10) which starts at 0 (default) and ends at 9 (one less than 10).
  • for i in range(1, 11):: Iterates from 1 to 10. It specifies the starting point of 1 and goes up to 10.
  • for i in range(1, 11, 2):: Iterates starting from 1 up to 10, incrementing by 2 each time, thus printing only odd numbers between 1 and 10.

The for loop in Python is an indispensable tool for iterating over sequences and performing repeated operations efficiently. By mastering this loop, along with utilities like the range() function, you can handle most common looping requirements with ease and clarity. Whether you’re processing items in a list, executing tasks a specific number of times, or combining it with conditions and other control structures, the for loop enhances readability and reduces the chance for errors in your code.

Python — while loop

The while loop in Python is a fundamental control structure used to repeatedly execute a block of code as long as a given condition is true. It's particularly useful for situations where the number of iterations is not known beforehand, such as processing user input or waiting for a condition to change. This loop keeps running the code block until the condition becomes false or is explicitly terminated with a control statement like break.

Syntax of the While Loop

The basic syntax of a while loop in Python is as follows:

while condition:
# block of code to execute repeatedly

Explanation:

  • condition: This is a boolean expression that determines whether the loop will execute again. If this condition evaluates to True, the code block within the loop will be executed. Once the condition evaluates to False, the loop stops.

Execution Flow

Example

# Initialize the counter
count = 0

# Condition to check
while count < 5:
print(f"Count is {count}")
count += 1 # Increment the counter

Explanation:

  • count = 0: Initializes a counter variable to 0.
  • while count < 5:: Starts a loop that will continue as long as count is less than 5.
  • print(f"Count is {count}"): Each loop iteration prints the current value of count.
  • count += 1: Increases count by 1 on each iteration, moving towards breaking the loop condition.

The while loop is a powerful tool in Python that allows for repetitive tasks to be performed with dynamic conditions. Understanding how to control the flow of a while loop is crucial for developing effective Python scripts that can handle varying runtime conditions efficiently. Whether you are looping a fixed number of times or indefinitely, the while loop provides the flexibility needed to achieve robust program behavior.

Python — Loop Control

Loop control statements in Python are used to modify the behavior of looping constructs (for or while loops). These statements enable developers to fine-tune the execution of loops based on specific conditions, facilitating more dynamic and responsive loop operations. The primary loop control statements in Python include break, continue, and pass.

Break Statement

The break statement immediately terminates the loop in which it is placed, regardless of the loop's condition. It is commonly used to exit a loop when a specific, often critical, condition is met.

Syntax

for item in iterable:
if condition:
break
  • for item in iterable:: Begins the loop, iterating over iterable.
  • if condition:: Checks if a specific condition is true.
  • break: If the condition is true, break is executed, which stops the loop immediately and exits it.

Example

# Finding and stopping at a specific number
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number == 4:
print("Number 4 found, stopping loop.")
break

Explanation:

  • The loop iterates through numbers.
  • When it finds the number 4, it prints a notification and executes break, stopping the loop early.

Continue Statement

The continue statement skips the rest of the code inside the loop for the current iteration and moves directly to the next iteration. It's useful for bypassing parts of the loop for certain conditions without stopping the loop entirely.

Syntax

for item in iterable:
if condition:
continue
# Code below is skipped for this iteration when condition is true
  • continue: This is used within the loop to skip the execution of remaining statements in the current iteration as soon as it is executed and continues with the next iteration.

Example

# Skipping even numbers and printing only odd numbers
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
continue
print(number) # This will print 1, 3, 5

Explanation:

  • The loop checks each number to see if it is even.
  • If a number is even, continue is triggered, skipping the print statement for that number and continuing with the next iteration.

Pass Statement

The pass statement performs no operation; it's a placeholder when a statement is required syntactically, but no action needs to be executed. This can be useful in stubs or when developing new code where the exact action isn't decided yet.

Syntax

for item in iterable:
if condition:
pass
# Code here always executes, regardless of the 'pass' statement
  • pass: Does nothing. It is used where a statement is syntactically needed to maintain the integrity of the code structure but without any operational impact.

Example

# Placeholder for future implementation
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
pass # Potential place for future logic
print(number) # This will print all numbers

Explanation:

  • The loop iterates through each number.
  • The pass statement is used for even numbers, suggesting a place where future logic might be implemented. However, it does not affect the loop's execution, and all numbers are printed.

Understanding and utilizing these loop control statements allow for sophisticated control over the execution flow within loops, enhancing the logic and efficiency of Python scripts. These tools are essential for creating flexible and robust looping mechanisms.

Python — for else and while else loop

In Python, the for-else and while-else loops incorporate an else clause that is somewhat unconventional when compared to similar constructs in other programming languages. This else clause executes only after the loop finishes its normal execution—meaning it runs to completion without being interrupted by a break statement.

This feature is particularly useful for scenarios where you need to confirm that a process was completed as expected without early termination.

Python — for-else Loop

The for-else loop is useful for situations where you need to process all items in a sequence and then perform some final action if and only if the entire sequence was processed. This is commonly used in search operations where the absence of a break statement can signify that an item was not found.

Syntax

for item in iterable:
# process item
else:
# Code to execute after loop concludes normally
  • for item in iterable: This initiates the loop. The loop variable item takes each value from the iterable one by one.
  • else: This keyword introduces a block that only executes if the loop exhausts the iterable without encountering a break statement.

Execution Flow

Basic Example without break

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Loop to process numbers
for number in numbers:
print(f"Processing number: {number}")
else:
# This will always execute as there is no 'break' in the loop
print("All numbers processed.")

Explanation:

  • Loop Iteration: The loop iterates over each element in the numbers list and prints it.
  • Else Execution: Since there is no break statement interrupting the loop, the else clause executes right after the loop finishes, indicating that all numbers have been processed.

Example with break

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Loop to find a specific number
for number in numbers:
if number == 3:
print("Number 3 found, stopping search.")
break
else:
# This will not execute because the loop was interrupted by 'break'
print("Number not found.")

Explanation:

  • Condition Check: The loop checks each number to see if it is 3.
  • break Execution: When it finds 3, it prints a message and executes a break, stopping the loop.
  • Else Non-execution: Because the loop was interrupted by the break, the else clause does not execute.

Python — while-else Loop

The while-else loop is ideal for performing a task repeatedly under a condition and executing an action afterwards if the loop wasn't prematurely stopped by a break.

Syntax

while condition:
# process
else:
# Code to execute after loop concludes normally
  • while condition: This line sets the condition for the loop to run. As long as the condition evaluates to True, the loop continues to execute.
  • else: Similar to the for-else structure, this part of the loop runs only if the while loop completes by the condition turning False and not if the loop is exited via a break statement.

Example with break

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Loop to find a specific number
for number in numbers:
if number == 3:
print("Number 3 found, stopping search.")
break
else:
# This will not execute because the loop was interrupted by 'break'
print("Number not found.")

Explanation:

  • Interrupt Condition: If count reaches 2, the loop prints a message and breaks.
  • Else Non-execution: Since the loop is interrupted by the break, the else block does not execute, signaling that the loop did not finish naturally.

These examples clearly illustrate how the else clause in Python loops adds a layer of logic that can handle both complete and interrupted loop executions. This functionality provides a powerful tool for managing loop outcomes based on whether they were able to run to completion.

Photo by Arthur Osipyan on Unsplash

--

--

Jeeshan
“Grokking Python Fundamentals”

Data Analyst Enthusiast | Unveiling Insights Through Numbers | Helping You Navigate the World of Data Science | Exploring the Frontiers of ML and Generative AI