For Loops
Python for loop¶
Here us the syntax
for
item
in
sequence:
Break, continue, and pass are control flow statements in Python that are used to change the behavior of loops (and in the case of pass, to do nothing).
Here's a short explanation of each item:
Break¶
break: Terminates the loop completely and transfers control to the first statement after the loop. This loop will print numbers 0 to 4 and then stop.
Continue¶
continue: Skips the rest of the code inside the current loop iteration and moves to the next iteration of the loop. This loop will print all odd numbers between 0 and 9.
Pass¶
pass: Does nothing and is used as a placeholder in loops, function definitions, or conditionals where syntactically some code is required but no action is needed. This loop will print numbers 5 to 9, doing nothing for numbers less than 5.
Else¶
else(used with loops): Executes when the loop completes normally (i.e., not terminated by abreakstatement). This will print numbers 0 to 4 and then "Loop completed without break".
Continue vs Break vs Pass¶
continue: Skips to the next iteration of the loop.break: Exits the loop immediately.pass: Does nothing, acts as a placeholder.
For loops Examples¶
| Code Examples | Code Examples |
|---|---|
# Print "Access Denied" 5 times
for _ in range(5):
print("Access Denied")
|
# Using list comprehension for conditional operations
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
|
# Using enumerate to get index and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
|
# Using zip to iterate over two lists
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
|
# Using a dictionary in a for loop
user_info = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in user_info.items():
print(f"{key}: {value}")
|
# Nested loops to print a multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i * j}")
print()
|
# Using the range function with a step
for i in range(0, 20, 5):
print(i)
|
# Using a set in a for loop
unique_numbers = {1, 2, 3, 4, 5}
for num in unique_numbers:
print(num)
|
# Using a for loop with else
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print("Found 3!")
break
else:
print("3 not found")
|
# Using a generator expression in a for loop
squares = (x * x for x in range(10))
for square in squares:
print(square)
|