Introduction

Welcome back to our Python tutorial series at CipherTrick.com! This tutorial will introduce you to loops in Python. Loops are an essential part of programming that allow a sequence of instructions to be executed repeatedly.

Part 1: For Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. Iterating over a sequence is called traversal.

Here’s the basic syntax of a for loop:

for element in sequence:
    # execute statements

Here’s an example of a for loop:

# Iterating over a list
for item in [1, 2, 3, 4, 5]:
    print(item)  # Outputs 1, 2, 3, 4, 5 on separate lines

Part 2: While Loop

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

Here’s the basic syntax of a while loop:

while condition:
    # execute statements

Here’s an example of a while loop:

# Initializing counter
count = 1

# While loop will keep executing until count is not less than 6
while count < 6:
    print(count)  # Outputs 1, 2, 3, 4, 5 on separate lines
    count += 1

Part 3: Loop Control Statements

Loop control statements change the execution from its normal sequence. Python supports the following control statements:

Conclusion

In this tutorial, we’ve learned about for and while loops in Python, and we’ve also touched upon control statements that help manage the flow of our loops. Mastering the use of loops can help you make your code more efficient, cleaner, and smarter. In the upcoming tutorials, we’ll continue exploring more Python concepts that will enhance your programming skills. As always, keep practicing and happy coding!