Loops in Python
Loops in Python are used to execute a block of code repeatedly as long as a certain condition is met. Python provides two main types of loops: for and while loops.
1. for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, or string) and execute a block of code for each element.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)Using range() with for Loop
The range() function generates a sequence of numbers.
for i in range(5): # Iterates from 0 to 4
print("Iteration:", i)2. while Loop
The while loop executes a block of code as long as the given condition is True.
count = 0
while count < 5:
print("Count:", count)
count += 13. Nested Loops
A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")4. Loop Control Statements
Python provides loop control statements to modify the flow of loops:
break Statement
The break statement stops the loop prematurely when a condition is met.
for num in range(10):
if num == 5:
break # Stops the loop when num is 5
print(num)continue Statement
The continue statement skips the current iteration and moves to the next.
for num in range(5):
if num == 2:
continue # Skips when num is 2
print(num)pass Statement
The pass statement is a placeholder that does nothing.
for i in range(3):
pass # Placeholder for future codeConclusion
Loops are essential for automation and iterative processing in Python. Understanding their behavior helps in writing efficient and effective code.