Loops in Programming: Repeating with For and While

Loops in Programming: Repeating with For and While

Welcome back to our programming tutorial series! Today, we’ll be exploring loops, an essential concept in programming that allows you to repeat a block of code multiple times. Loops enable you to handle repetitive tasks efficiently, making your code more compact and powerful.


What Are Loops? #

Loops are control structures that let you execute a block of code repeatedly, either for a specified number of times or until a particular condition is met. In Python, the two most commonly used loops are for and while loops.


For Loops: Iterating Through Sequences #

A for loop is used to iterate over a sequence (such as a list, tuple, or string) or any other iterable object. The loop runs once for each item in the sequence.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

In this example, the loop iterates over each element in the fruits list and prints it.

Range Function in For Loops #

The range() function is often used with for loops to generate a sequence of numbers. It can be useful when you want to loop a specific number of times.

for i in range(5):
    print(i)

This will output numbers 0 through 4, as range(5) generates numbers from 0 to 4.


While Loops: Repeating Based on Conditions #

A while loop keeps executing as long as a given condition is true. It’s useful when you don’t know beforehand how many times you need to loop.

count = 0

while count < 5:
    print(count)
    count += 1

This loop continues to run as long as the count variable is less than 5.

Infinite Loops #

Be careful with while loops! If the condition never becomes False, the loop will run forever (an infinite loop). You can prevent this by ensuring the loop condition will eventually become False.


Nested Loops: Loops Inside Loops #

You can place one loop inside another to create nested loops. Nested loops are often used when working with multi-dimensional data, like matrices.

for i in range(3):
    for j in range(2):
        print(f"i = {i}, j = {j}")

This example has an outer for loop that runs 3 times, and for each iteration of the outer loop, the inner for loop runs 2 times.


Break and Continue: Controlling Loop Flow #

You can control how loops behave using break and continue statements:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and continues with the next one.

Break Example: #

for i in range(10):
    if i == 5:
        break
    print(i)

This loop will print numbers 0 through 4, then stop when i equals 5.

Continue Example: #

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

This loop skips even numbers and only prints odd numbers.


Practical Exercise: Build a Multiplication Table #

Now that you understand how loops work, try this exercise:

  1. Write a program that generates a multiplication table (from 1 to 10) using nested loops.
  2. Use a for loop to iterate through the rows (1 to 10).
  3. Inside the loop, use another for loop to iterate through the columns and print the product of the row and column numbers.

Here’s a starter example:

for i in range(1, 11):
    for j in range(1, 11):
        print(f"{i} x {j} = {i * j}")

Test this by running the program and reviewing the multiplication table it generates!


What’s Next? #

You’ve just learned how to repeat actions using for and while loops! Loops are essential for handling repetitive tasks efficiently, and they are used in almost every program you’ll write.

In the next post, we’ll dive into functions, which allow you to organize your code into reusable blocks. Stay tuned!



Happy coding, and we’ll see you in the next lesson!

comments powered by Disqus