As the seasons recur in predictable patterns, so do computational tasks in the world of programming. This cyclical nature finds its expression in loops—a mechanism that allows tasks to be repeated, much like the rhythmic cadence of a heart or the unwavering cycle of day and night. I urge you, dear reader, to actively engage with the examples. Create, modify, and experiment. Let the loops not just run on your machines but also in your minds, allowing their repetition to carve a deeper understanding.
The While Loop: The Persistent Seeker
The `while` loop can be likened to a philosopher in deep contemplation, repeatedly pondering a question until an answer is found. It continues as long as a certain condition remains true.
count = 0
while count
This loop prints numbers from 0 to 4. It continues as long as the variable `count` is less than 5.
The For Loop: The Ordered Traveler
The `for` loop moves with precision and order, much like a dancer performing a choreographed routine. It iterates over a sequence (like a list or range) and executes its block for each item in that sequence.
for i in range(5):
print(i)
Again, the numbers from 0 to 4 are printed, but this time using the clarity and structure of the `for` loop.
Break and Continue: The Art of Choice
Even within loops, there are moments of choice—to proceed or to halt, to skip or to continue. The `break` statement exits the loop prematurely, while `continue` skips to the next iteration.
for i in range(5):
if i == 3:
break
print(i)
This loop stops when it encounters the number 3, demonstrating the power of choice in the midst of repetition.
Meditation
Loops, in their persistent repetition, echo the enduring cycles of nature and life. As you embrace loops in your coding journey, may you also reflect upon the loops in your own life—those patterns of thought and action that shape your days. May your computational loops be as fruitful and purposeful as the life cycles you seek to cultivate.
Exercises
1. Write a loop that prints all numbers between 1 and 10.
Solution
for i in range(1, 11):
print(i)
2. Write a loop that prints all numbers between 10 and 1 in reverse order.
Solution
for i in range(10, 0, -1):
print(i)
3. Create a while
loop that sums all numbers up to 100.
Solution
sum = 0
i = 1
while i
4. Use a for
loop to find the product of all numbers between 1 and 5.
Solution
product = 1
for i in range(1, 6):
product *= i
print(product)
5. Write a while
loop that adds numbers from 50 to 60 (inclusive).
Solution
sum = 0
i = 50
while i
6. Design a loop that prints out a triangle of asterisks, with its height as 5.
Solution
for i in range(1, 6):
print('*' * i)
7. Create a nested loop to print a square grid of numbers, with sides of length 4.
Solution
for i in range(1, 5):
for j in range(1, 5):
print(j, end=" ")
print()