Introduction

Hello and welcome back to our Python series on CipherTrick.com! Today, we’re going to take a detailed look at ‘for’ loops in Python. ‘For’ loops are a vital control flow tool in Python, used for repeating a block of code a specified number of times.

Part 1: The Basics of ‘For’ Loops

A ‘for’ loop in Python iterates over a sequence (like a list, tuple, or string) or other iterable objects. In the process, the loop variable is assigned the value of each sequence item in turn.

Here’s a basic ‘for’ loop:

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

This code prints numbers from 0 to 4, each on a new line. range(5) generates a sequence of numbers from 0 up to (but not including) 5, and i takes on each of these values in order.

Part 2: Iterating over Lists, Tuples, and Strings

‘For’ loops are often used to iterate over lists, tuples, and strings:

# List iteration
for fruit in ['apple', 'banana', 'cherry']:
    print(fruit)

# Tuple iteration
for num in (1, 2, 3):
    print(num)

# String iteration
for char in 'Hello':
    print(char)

Part 3: The ‘break’ and ‘continue’ Statements

Python provides two control statements that can change the flow of ‘for’ loop execution: ‘break’ and ‘continue’.

The break statement allows you to exit the loop prematurely when a certain condition is met:

for i in range(10):
    if i == 5:
        break
    print(i)

The continue statement, on the other hand, allows you to skip the rest of the current loop iteration and immediately proceed to the next one:

for i in range(10):
    if i == 5:
        continue
    print(i)

Conclusion

Understanding ‘for’ loops is an important step on your Python journey. They provide a convenient way to repeat a block of code a specified number of times and allow you to traverse sequences and other iterable objects with ease. Continue practicing and experimenting with ‘for’ loops in different scenarios to increase your confidence and proficiency. In our next tutorial, we’ll explore ‘while’ loops in more detail. Until then, happy coding!