[Latest] Python for Loops with Examples – Easiest Tutorial – 2024

Hey guys, in today’s blog we are going to see Python for Loops. Loops are an integral part of programming, allowing us to perform repetitive tasks efficiently. In Python, loops play a vital role in iterating over data structures, performing calculations, and automating tasks. They provide a concise and elegant way to execute a block of code repeatedly until a certain condition is met.

Python offers two types of loops: the “for” loop and the “while” loop. In this article, we will delve into the world of loops in Python, exploring their syntax, use cases, and best practices.

Python For Loop

Python for loops

Python for loop is used when we know the number of times we want to iterate over a sequence or collection. It is commonly used for iterating over lists, tuples, strings, and other iterable objects. The basic syntax of a for loop in Python is as follows:

# Python for loop

for item in sequence:
    # code block

Let’s look at a practical example to understand the concept better. Suppose we have a list of names, and we want to print each name on a new line:

# Python for loop

names = ["Alice", "Bob", "Charlie", "Dave"]
for name in names:
    print(name)

Output

Alice
Bob
Charlie
Dave

In this example, the loop iterates over the “names” list and assigns each value to the variable “name” successively. The code block within the loop, indicated by the indentation, is executed for each iteration, printing the name on the console. The loop continues until all the items in the list have been processed.

The range() function is often used in conjunction with for loops to generate a sequence of numbers. For instance, to print the numbers from 1 to 10, we can use the following code:

# Python for loop

for i in range(1, 11):
    print(i)

Output

1
2
3
4
5
6
7
8
9
10

In this case, the range function generates a sequence of numbers from 1 to 10 (excluding 11), and the loop iterates over each number, printing it on a separate line.

Python While Loop

Python While Loops - Python For Loops

The “while” loop in Python is used when the number of iterations is uncertain, and the loop continues until a specified condition becomes False. It repeatedly executes a block of code as long as the condition remains true. The general structure of a while loop is as follows:

# Python while loop

while condition:
    # code block

Let’s consider an example where we want to find the first power of 2 that exceeds 1000:

# Python while loop

num = 1
power = 0
while num <= 1000:
    num = 2 ** power
    power += 1
print("The first power of 2 exceeding 1000 is", num)


Output

The first power of 2 exceeding 1000 is 1024

In this code snippet, the loop starts with a variable “num” initialized to 1 and a variable “power” set to 0. The loop continues until “num” exceeds 1000. In each iteration, the value of “num” is updated by calculating 2 raised to the power. Finally, the loop terminates, and the program prints the result.

Loop Control Statements

Python provides certain control statements to alter the behavior of loops. Two frequently used control statements are “break” and “continue”. These statements can be useful when you want to exit a loop prematurely or skip certain iterations based on specific conditions.

Break Statement

The “break” statement immediately terminates the loop, skipping any remaining iterations.

# Python break statement

for i in range(1,11):
    if i==5:
        break
    print(i)

Output

1
2
3
4

Continue Statement

On the other hand, the “continue” statement skips the current iteration and proceeds to the next iteration.

# Python continue statement

for i in range(1,11):
    if i==5:
        continue
    print(i)
1
2
3
4
6
7
8
9
10

Loop Best Practices

To make your code more readable and efficient, it’s essential to follow some best practices when using loops in Python:

  1. Choose the appropriate loop: Use the “for” loop when the number of iterations is known and the “while” loop when it depends on a condition.
  2. Initialize variables before the loop: Initialize variables outside the loop whenever possible to prevent redundant assignments.
  3. Avoid infinite loops: Ensure that the loop has a well-defined exit condition to avoid infinite loops that can freeze your program.
  4. Use descriptive variable names: Use meaningful names for variables within loops to enhance code readability and maintainability.
  5. Optimize performance: If performance is a concern, try to minimize costly operations within the loop by moving them outside, if possible.
  6. Be mindful of indentation: Python relies on proper indentation to define the scope of the loop. Incorrect indentation can lead to syntax errors.

Conclusion

In conclusion, loops are powerful constructs that enable us to repeat a block of code in an efficient and controlled manner. Python provides the “for” and “while” loops, each with its own specific use cases. By understanding their syntax, combining them with control statements, and following best practices, you can leverage loops to create more concise and effective programs. So, embrace the power of loops and unlock new possibilities in your Python programming journey.

So this was all for Python for Loops. If you have any doubt regarding this, you can contact me by mail.

Check out our other Python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *