What are loops in programming?
sobes.tech AI
Answer from AI
Loops are control structures that allow you to execute a block of code multiple times until a certain condition is met or until the elements in a sequence are exhausted.
In Python, there are three main types of loops:
whilefor- Loops using generators and iterators (although this is more of a concept based on
for)
while loop
Executes a block of code as long as the condition is true.
# Example of a while loop
count = 0
while count < 5:
print(f"Iteration {count}")
count += 1
for loop
Iterates over elements of a sequence (list, tuple, string, dictionary, etc.) or an iterable object.
# Example of a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for can be used with the range() function to perform a specific number of iterations.
# Example of a for loop with range()
for i in range(3):
print(f"Just number: {i}")
Keywords for controlling loops:
break: Completely terminates the loop.continue: Skips the remaining part of the current iteration and proceeds to the next.
# Example of break
for i in range(10):
if i == 5:
break # Exit the loop
print(i)
# Example of continue
for i in range(10):
if i % 2 == 0:
continue # Proceed to the next iteration
print(i)
else clause in loops:
In Python, for and while loops can have an optional else block. This block executes only if the loop terminates naturally (i.e., not interrupted by break).
# Example of else with for
for i in range(3):
print(f"Inside loop: {i}")
else:
print("Loop finished without break")
# Example of else with while
count = 0
while count < 3:
print(f"Counter: {count}")
count += 1
else:
print("Condition became false")
Loops and iterators/generators:
The for loop in Python actually works using the iterator protocol. Any object implementing __iter__() and __next__() methods can be used in a for loop. Generators are a convenient way to create iterators.
# Example of a simple generator
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
Comparison of for and while:
| Feature | for |
while |
|---|---|---|
| Purpose | Iterate over a sequence/iterator | Execute as long as the condition is true |
| Termination | Exhaustion of elements / break |
Condition becomes false / break |
| Usage | When the number of iterations is known or when iterating over a collection | When the number of iterations is unknown in advance |
The choice of loop type depends on the specific task.