Geek Slack

Introduction to Python
About Lesson



Python For Loops


Python For Loops

A 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 item in the sequence.

1. Basic For Loop

The basic syntax of a for loop is:

for item in sequence:
    # code block

The code block inside the loop will be executed once for each item in the sequence.

Example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

2. Using Range() Function

The range() function generates a sequence of numbers that can be used in a for loop.

Example:

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

3. Looping Through a String

A for loop can also be used to iterate through each character in a string.

Example:

for char in "Python":
    print(char)

4. Using Break Statement

The break statement can be used to exit the loop prematurely based on a certain condition.

Example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
    if fruit == 'banana':
        break

5. Using Continue Statement

The continue statement can be used to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration.

Example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    if fruit == 'banana':
        continue
    print(fruit)

Conclusion

For loops are commonly used in Python for iterating over sequences and performing operations on each item. Understanding how to use for loops effectively is essential for writing efficient and concise code.

Join the conversation