Basics

Python For Loops

For Loops in Python

Python for loops iterate over ranges or lists, with else clauses.

Introduction to Python For Loops

In Python, for loops are used to iterate over sequences such as lists, tuples, strings, or ranges. They allow you to execute a block of code repeatedly for every element in a sequence.

Unlike while loops, which continue until a condition is false, for loops iterate over items of a sequence in the order they appear.

Basic Syntax of a For Loop

The basic syntax of a for loop in Python is straightforward. Here is the general format:

for variable in sequence:
    block of code

Here, variable is a name that represents the current item of the sequence, and sequence is the collection of items you are iterating over. The block of code will execute once for each item in the sequence.

Iterating Over a List

One common use of for loops is to iterate over the elements of a list. Here's an example:

In this example, the loop iterates over the list fruits and prints each fruit in the list.

Using the Range Function

The range() function is often used in for loops to generate a sequence of numbers. Here's how it works:

This loop will print numbers from 0 to 4. The range(5) function generates numbers starting from 0 up to, but not including, 5.

For Loop with Else Clause

Python for loops can also be followed by an else clause. The block of code inside the else clause will be executed when the loop has exhausted iterating over the sequence. Here's an example:

In this example, the else clause prints a message after the loop finishes iterating through the range.

Conclusion

Python for loops are a powerful tool for iterating over sequences. They are simple to use and can be combined with the else clause for additional logic after the loop completes. Understanding how to use for loops effectively will help you manage collections of data in Python efficiently.

In the next post, we will delve into Python Lists to understand how they can be created and manipulated.

Previous
While Loops
Next
Lists