Loops (for and while)
Loops in Python are used to repeatedly execute a block of code. They allow you to automate repetitive tasks and process data efficiently. Python provides two primary types of loops: for
and while
.
1. The for
Loop
The for
loop is used for iterating over a sequence (such as a list, tuple, string, or range) and executing a block of code for each item in the sequence. Here's the basic syntax:
for variable in sequence:
# Code to be executed for each item in the sequence
For example, iterating through a list of numbers:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This for
loop will execute the indented code block for each element in the numbers
list.
2. The while
Loop
The while
loop is used to repeatedly execute a block of code as long as a specified condition is true. Here's the basic syntax:
while condition:
# Code to be executed while the condition is True
For example, using a while
loop to count from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
The while
loop will continue executing the code as long as the condition count <= 5
is true.
3. Loop Control Statements
Both for
and while
loops support loop control statements:
-
break
: Terminates the loop prematurely, even if the loop condition is still true. -
continue
: Skips the rest of the current iteration and moves to the next iteration. -
pass
: Acts as a placeholder, allowing you to write a loop with no content for testing or future implementation.
4. Nested Loops
Python allows you to nest loops, which means placing one loop inside another. This is useful for working with two-dimensional data or creating more complex iterations.
For example, using nested loops to create a multiplication table:
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end='\t')
print()
This code uses nested for
loops to generate a multiplication table from 1 to 5.
Loops are essential for automating repetitive tasks, processing large datasets, and iterating through collections of data. They help make your Python programs more dynamic and efficient.