Loops in Python: A Quick Guide to for
and while
Loops
Loops are a fundamental part of any programming language, allowing you to execute a block of code repeatedly without writing the same code multiple times. In Python, the two main types of loops are for
and while
loops. Understanding how to use these loops effectively is crucial for writing clean, efficient, and readable code. Let’s explore how these loops work in Python!
for
Loop
The for
loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) and execute a block of code for each element in that sequence. It's particularly useful when you know the number of iterations in advance.
Syntax:
for element in sequence:
# Code block to be executed
Example:
# Iterating over a list
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Output:
1
2
3
4
5
In this example, the for
loop iterates over each number in the numbers
list and prints it.
while
Loop
The while
loop is used when you want to execute a block of code as long as a condition is true. It’s perfect for situations where the number of iterations isn’t known beforehand and depends on…