Loops in Python are used to execute a block of code multiple times until a specified condition is met. Python provides two primary types of loops: for
and while
. Additionally, Python offers control statements like break
, continue
, and pass
to manage loop execution efficiently.
1. The for
Loop #
The for
loop in Python is used for iterating over a sequence (list, tuple, dictionary, set, or string).
Syntax: #
for variable in sequence:
# Code to execute
Example: Iterating over a list #
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Example: Using range()
in a for
loop #
for i in range(5):
print(i)
Example: Iterating over a dictionary #
student = {"name": "Alice", "age": 25, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
2. The while
Loop #
The while
loop executes a block of code as long as a specified condition is True
.
Syntax: #
while condition:
# Code to execute
Example: Counting using a while loop #
count = 0
while count < 5:
print(count)
count += 1
Example: Using break
in a while
loop #
num = 1
while num < 10:
if num == 5:
break
print(num)
num += 1
3. Loop Control Statements #
a. break
Statement #
Terminates the loop when encountered.
for i in range(10):
if i == 5:
break
print(i)
b. continue
Statement #
Skips the current iteration and moves to the next.
for i in range(10):
if i == 5:
continue
print(i)
c. pass
Statement #
A placeholder used when a statement is syntactically required but no action is needed.
for i in range(5):
if i == 3:
pass # Placeholder for future implementation
print(i)
4. Nested Loops #
A loop inside another loop.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
5. List Comprehension with Loops #
Python provides a concise way to create lists using loops.
squares = [x**2 for x in range(5)]
print(squares)
6. Infinite Loops #
Avoid infinite loops by ensuring the loop condition eventually becomes False
.
while True:
response = input("Type 'exit' to stop: ")
if response == "exit":
break
Conclusion #
Python loops provide an efficient way to automate repetitive tasks. By mastering for
and while
loops, along with control statements, you can write more efficient and readable code.