Python Crash Course for Beginners | A Comprehensive Guide to Python ‘for’ Loop

Python Crash Course for Beginners | A Comprehensive Guide to Python ‘for’ Loop

 

Iteration is a fundamental concept in programming, allowing developers to execute a block of code multiple times. The Python for loop is a primary tool for implementing iteration, providing a way to traverse through a sequence and execute a block of code for each element in the sequence. In this article, we will delve into the Python for loop, offering coding examples and explanations to help you understand its functionality and usage.

Python for Loop Basics

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence.

Syntax

The general syntax for the Python for loop is as follows:

for variable in sequence:
    # Code to execute for each element in the sequence

The ‘sequence’ can be any iterable object, and the ‘variable’ is a temporary placeholder that takes on the value of each element in the sequence during the iteration.

Example 1: Simple for Loop with a List

Let’s begin with a simple example to understand the basic usage of the for loop in Python.

fruits = ["apple", "banana", "orange", "grape"]

for fruit in fruits:
    print(fruit)

In this example, the ‘fruits’ list contains four string elements. The for loop iterates through each element in the ‘fruits’ list and prints the element. The output will be:

apple
banana
orange
grape

Python for Loop with range() Function

Often, you may want to repeat a block of code for a specific number of times. The range() function is a convenient tool for generating a sequence of numbers that can be used in conjunction with a for loop.

Syntax

The range() function can be used in three ways:

     range(stop): Generates a sequence of numbers from 0 (inclusive) to stop (exclusive)

     range(start, stop): Generates a sequence of numbers from start (inclusive) to stop (exclusive)

     range(start, stop, step): Generates a sequence of numbers from start (inclusive) to stop (exclusive), incrementing by the step value

Example 2: for Loop with range()

Let’s look at an example that demonstrates the use of the for loop with the range() function.

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

In this example, the range() function generates a sequence of numbers from 0 to 4. The for loop iterates through each number in the sequence and prints it. The output will be:

0
1
2
3
4

Python for Loop with else Block

Python allows you to use an optional else block with the for loop. The code within the else block is executed once the for loop has completed its iteration through the sequence. This can be useful for performing certain actions after the loop is finished.

Syntax

The general syntax for the Python for loop with an else block is as follows:

for variable in sequence:
    # Code to execute for each element in the sequence
else:
    # Code to execute after the for loop has completed its iteration

Example 3: for Loop with else Block

Here’s an example illustrating the use of the else block with a for loop:

names = ["Alice", "Bob", "Charlie"]

for name in names:
    print(name)
else:
    print("All names have been printed.")

In this example, the for loop iterates through each element in the ‘names’ list and prints it. Once the loop has completed its iteration, the code within the else block is executed, and the program prints “All names have been printed.” The output will be:

Alice
Bob
Charlie
All names have been printed.

Nested for Loops

Sometimes, you may need to iterate through multiple sequences or perform iterations within an iteration. In such cases, you can use nested for loops, which are essentially for loops within other for loops.

Syntax

The general syntax for nested for loops is as follows:

for variable_1 in sequence_1:
    # Code to execute for each element in sequence_1
    for variable_2 in sequence_2:
        # Code to execute for each element in sequence_2

Example 4: Nested for Loop

Let’s look at an example that demonstrates the use of nested for loops in Python.

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

for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

In this example, the ‘matrix’ is a list of lists, representing a 3×3 matrix. The outer for loop iterates through each row in the matrix, while the inner for loop iterates through each element within the row. The program prints each element followed by a space, and a new line is printed after each row. The output will be:

1 2 3
4 5 6
7 8 9

The Python for loop is a powerful tool for controlling the flow of a program through iteration. By understanding and mastering the basic for loop, for loop with range(), for loop with else block, and nested for loops, you can create more efficient and versatile applications.

In this article, we explored the Python for loop with examples and explanations to help you grasp its functionality and usage. With practice, you’ll be able to apply these concepts in your own projects, enhancing your ability to work with sequences and perform repeated tasks.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!