In Python, you can create loops using two main types of loops: for
loops and while
loops. Here's how you can write each type of loop:
For loops are used to iterate over a sequence (like a list, tuple, or string) or other iterable objects.
for item in sequence:
# code block to execute for each item
Example:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
While loops execute a block of code as long as a specific condition is true.
while condition:
# code block to execute
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Be careful with while loops as if the condition never becomes false, it can lead to infinite loops.
Additionally, you can use the break
and continue
statements to control loop flow. The break
statement is used to exit the loop, and the continue
statement skips the current iteration and moves to the next one.
Example (break):
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
Output:
0
1
2
3
4
Example (continue):
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers and print odd numbers only
print(i)
Output:
1
3
5
7
9