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.
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
All Notebooks in One Bundle: Data Science Recipes and Examples in Python & R.
End-to-End Python Machine Learning Recipes & Examples.
End-to-End R Machine Learning Recipes & Examples.
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.