Learn Python

For Loop In Python

A for loop in Python is a handy way to go through a sequence (like a list, tuple, or string) or other iterable things. In this guide, we’ll go through the basics of for loops and show you how to use them.


for variable in iterable:
    # Code to be executed in each iteration

The syntax of a for loop is used for iterating over a sequence or iterable. It assigns each item in the iterable to the variable, and the indented code block is executed for each iteration.

Using range() Function

# Example: Printing numbers 0 to 4
for i in range(5):

The range() function generates a sequence of numbers. This is often used with for loop to perform a specific number of iterations. In the example, it prints numbers from 0 to 4.

Iterating Over Lists

# Example: Iterating over a list of fruits
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print("I like", fruit)

for loops are commonly used to iterate over the elements of a list. In the example, it iterates over a list of fruits, printing each fruit in the list one by one.

Nested For Loops

# Simple program using nested for loops to print a rectangle of stars
for i in range(3):  # Outer loop for rows
    for j in range(5):  # Inner loop for columns
        print('*', end=' ')
    print()  # Move to the next line after each row

This program uses nested for loops to create a simple rectangular pattern, The outer loop (for i in range(3)) iterates over three rows and the inner loop (for j in range(5)) iterates over five columns for each row.

Feel free to expirement and adjust the values to print different patterns.

Break And Continue

# Example: Using break and continue in a for loop
for i in range(10):
    if i == 5:
    elif i % 2 == 0:

break is used to exit the loop without completing it. In the example, the loop breaks when i is equal to 5. and continue is used to skip the rest of the code in the current iteration. In the example, it skips even numbers.

So this was all the basic of for loops you needed to know.