Loops are powerful constructs in programming that allow you to repeat a block of code multiple times. They are essential for automating repetitive tasks and processing collections of data efficiently.
Key Concept: Loops
Loops help you avoid writing the same code multiple times, making your programs more efficient and easier to maintain.
In Python, there are two main types of loops:
- While Loops: Execute a block of code as long as a condition is true.
- For Loops: Iterate over a sequence (like a list, tuple, or string) or other iterable objects.
Comparing While and For Loops
Let's look at an example that demonstrates both types of loops achieving the same result:
Both loops print numbers from 0 to 5, but they do so in slightly different ways:
- The for loop uses the range() function to generate a sequence of numbers.
- The while loop uses a counter variable that we manually increment.
Guided Exercise: Modifying Loops
Now, let's practice by modifying these loops. Follow these steps:
- Change both loops to print numbers from 1 to 5 instead of 0 to 5.
- Add a print statement after each loop to separate their outputs.
- For the while loop, add a condition to print "Halfway there!" when the counter reaches 3.
# Modify these loops to print numbers from 1 to 5
# For loop
print("For loop:")
for x in range(1, 6):
print(x)
print("\nWhile loop:")
# While loop
y = 1
while y <= 5:
print(y)
if y == 3:
print("Halfway there!")
y += 1
print("\nBoth loops completed!")