8. Loops: Automating repetition

Quiz: 0/5

Have you ever needed to perform an action repeatedly, like counting numbers or displaying a message multiple times? Instead of duplicating code, loops offer a more efficient and elegant way to automate repetition in Python.

Python provides two main types of loops: for loops and while loops. Let’s explore how they work and how you can use them effectively!

What are loops?

Loops allow you to write a block of code once and execute it multiple times. They are invaluable for automating repetitive tasks, saving time and effort. Let’s dive into the two main types of loops in Python.

for loops: Iterating over a sequence

A for loop repeats an action for every item in a sequence, such as a list, string, or range of numbers.

Syntax

for item in sequence:
    # Do something with item

Example: Iterating over a list

for number in [1, 2, 3, 4, 5]:
    print("This is number:", number)

Explanation:
The loop iterates over the list [1, 2, 3, 4, 5]. During each iteration, the variable number takes one value from the list, which is then printed.

Using range() with for loops

If you need a sequence of numbers but don’t have a predefined list, use the range() function. It generates a sequence of numbers.

Example:

for i in range(5):
    print("Hello!")

Explanation:
range(5) generates numbers from 0 to 4. The loop runs five times, printing "Hello!" on each iteration.

while loops: Repeating based on a condition

A while loop continues executing as long as a specified condition is True. Be careful to ensure the condition eventually becomes False; otherwise, you’ll create an infinite loop!

Syntax

while condition:
    # Do something

Example: Counting with a condition

counter = 1
while counter <= 5:
    print("Counting:", counter)
    counter += 1

Explanation:
This loop prints numbers from 1 to 5. The variable counter increments by 1 on each iteration. When counter reaches 6, the condition counter <= 5 becomes False, and the loop ends.

Controlling loops

Breaking out of a loop with break

The break statement allows you to exit a loop prematurely when a certain condition is met.

Example:

for number in range(10):
    if number == 5:
        break  # Exit the loop when number equals 5
    print(number)

Output:

0  
1  
2  
3  
4  

Explanation:
The loop stops when number equals 5, skipping any further iterations.

Skipping iterations with continue

The continue statement skips the rest of the loop’s code for the current iteration and moves to the next one.

Example:

for number in range(5):
    if number == 2:
        continue  # Skip when number equals 2
    print(number)

Output:

0  
1  
3  
4  

Explanation:
The loop skips printing the number 2 due to the continue statement.

Practical examples

Example 1: Calculating the sum of numbers

total = 0
for number in range(1, 6):  # Numbers 1 to 5
    total += number
print("Total:", total)

Output:

Total: 15

Explanation:
The loop adds each number from 1 to 5 to the variable total, which accumulates the sum.

Example 2: Password check

password = "secret"
attempt = ""
attempts = 0

while attempt != password and attempts < 3:
    attempt = input("Enter password: ")
    attempts += 1

if attempt == password:
    print("Access granted!")
else:
    print("Access denied!")

Explanation:
The loop allows up to three attempts to guess the password. If the user enters the correct password within three tries, access is granted. Otherwise, it is denied.

Best practices for using loops

Avoid infinite loops

Ensure that conditions in while loops will eventually become False.

# Avoid this!
while True:
    print("This never ends!")

Use descriptive loop variables

Choose variable names that clearly describe their role in the loop.

# Good
for student in students:
    print(student)

# Vague
for s in students:
    print(s)

Optimize range() usage

Customize the range() function with start, stop, and step values.

for i in range(2, 10, 2):  # Start at 2, go up to 10, increment by 2
    print(i)

Conclusion

Loops are essential tools in programming. They enable you to automate repetitive tasks efficiently, whether by iterating over sequences with for loops or running tasks until a condition is met with while loops.

By mastering break and continue, you can refine how loops execute, empowering you to handle a wide variety of programming challenges effectively. Practice using loops in different scenarios to build confidence and write cleaner, more efficient code!

Hands-On Practise

Exercise: Multiplication table

Objective: Practice using for loops, while loops, and the break statement by creating a static multiplication table for a fixed number.

Problem Statement:

  1. Write a program to:
    • Generate the multiplication table for the number 7.
    • Use a for loop to calculate and display each product in the format 7 x i = product.
    • Stop the loop if the product exceeds 50 using a break statement.

Hints:

  • Use range(1, 11) to generate the numbers from 1 to 10.
  • Use an if condition inside the loop to check if the product exceeds 50. If true, use break to exit the loop.
Output:

Quizzes: 0/5

Question 1:

Which statement is used to exit a loop immediately in Python?

  • continue
  • exit
  • break
  • pass

Question 2:

What does the 'range(5)' function generate?

  • Numbers from 1 to 5
  • Numbers from 0 to 5
  • Numbers from 0 to 4
  • Numbers from 1 to 6

Question 3:

What happens when the 'continue' statement is executed in a loop?

  • The loop stops immediately.
  • The loop skips to the next iteration.
  • The loop restarts from the beginning.
  • The loop raises an error.

Question 4:

In a 'while' loop, what happens if the condition is always true?

  • The loop runs forever.
  • The loop runs only once.
  • The loop doesn't run at all.
  • The loop raises an exception.

Question 5:

What is the output of the following code? for i in range(3): if i == 1: continue print(i)

  • 0 1 2
  • 0 2
  • 1 2
  • 0 1

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonConditional statementsNext lessonIntroduction to Strings