Mastering Loops in Python

Python

Today, we’ll delve into loops – a way to repeatedly execute code based on conditions.

We’ll connect this with our previous topics: conditional statements (if, else, elif) and basic Python concepts.

Understanding while Loops

A while loop in Python repeatedly executes a target statement as long as a given condition is true.

Example 1: Basic while Loop

Python
counter = 0
while counter < 5:
    print("Counter is", counter)
    counter += 1

This loop prints the value of counter and then increments it by 1. The loop continues until counter is no longer less than 5.

Think of this as reading chapters in a book. You keep reading (looping) until you reach chapter 5, and then you stop.

while Loop with a Break Statement

Sometimes, you might want to exit a while loop before the condition becomes false.

Example 2: while Loop with break

Python
counter = 0
while True:
    print("Counter is", counter)
    if counter == 3:
        break
    counter += 1

This loop will run indefinitely due to while True, but it breaks when counter equals 3.

It’s like saying, “Continue walking until I say stop. Stop when you reach the third step.”

Exploring for Loops

The for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).

Example 3: Basic for Loop

Python
for number in range(5):
    print(number)

This loop iterates over a sequence of numbers (0 to 4) and prints each number.

Imagine a to-do list with 5 tasks. You go through each task one by one and mark it done.

for Loop with a List

You can also iterate over the elements of a list using a for loop.

Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print("I like", fruit)

This loop iterates through each item in the fruits list and prints a statement about each fruit.

Consider a basket of fruits. You pick each fruit and say, “I like [fruit].”

The range Function

The range function generates a sequence of numbers. It’s like a Python way of saying, “Hey, give me numbers from here to there!” It’s particularly useful in loops for repeating actions a certain number of times.

How Does range Work?

range can take up to three arguments:

  1. Start: Where to start the sequence (inclusive). If omitted, it defaults to 0.
  2. Stop: Where to end the sequence (exclusive – it doesn’t include the stop number).
  3. Step: The difference between each number in the sequence. If omitted, it defaults to 1.

Basic Example

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

This prints numbers from 0 to 4. Notice how it starts from 0 (default start) and stops before 5.

With Start and Stop

Python
for i in range(2, 6):
    print(i)

Here, you get numbers from 2 to 5. It starts at 2 and stops before 6.

Adding Step

Python
for i in range(0, 10, 2):
    print(i)

This prints even numbers from 0 to 8. It steps 2 numbers at a time, starting from 0.

Creative Use of range

You can even use range backwards!

Python
for countdown in range(10, 0, -1):
    print(f"Launching in: {countdown}")
print("Blast off! 🚀")

This code creates a countdown from 10 to 1, perfect for a rocket launch simulation!

Why Use range with for Loops?

  • Iteration: It’s perfect for executing a block of code multiple times.
  • Control: You have precise control over the number of iterations.

Understanding Nested Loops

Nested loops are loops inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop.”

Example 5: Nested Loops

Python
for i in range(3):
    for j in range(2):
        print("i =", i, ", j =", j)

For each value of i (0, 1, 2), the inner loop runs completely, iterating j over (0, 1).

Think of it as a clock. For every hour (i), the minute hand (j) completes a full cycle from 0 to 59.

Combining Loops with Conditional Statements

Example: while and for Loops with if-else

Let’s create a scenario where we use both while and for loops with if-else statements.

Example: Classroom Age Groups

Python
ages = [6, 11, 16, 20, 23]
group = 0
while group < len(ages):
    age = ages[group]
    if age < 13:
        print("Child in group", group)
    elif age < 18:
        print("Teenager in group", group)
    else:
        print("Adult in group", group)
    group += 1

This Python above categorizes a list of ages into three groups: children, teenagers, and adults. Here’s a step-by-step explanation:

  1. Initialization of Variables:
    • ages = [6, 11, 16, 20, 23]: This is a list containing ages.
    • group = 0: This is a counter initialized to 0. It will be used to keep track of the current index in the ages list.
  2. While Loop:
    • while group < len(ages): This loop will run as long as group (the index) is less than the length of the ages list. The length of ages is 5 (indices 0 to 4), so the loop will iterate five times.
  3. Inside the Loop:
    • age = ages[group]: This line gets the age at the current index (group) from the ages list.
    • The if-elif-else statement then categorizes the age into one of three groups:
      • if age < 13: If the age is less than 13, it prints “Child in group [group number]”.
      • elif age < 18: If the age is 13 or older but less than 18, it prints “Teenager in group [group number]”.
      • else: If the age is 18 or older, it prints “Adult in group [group number]”.
    • group += 1: This increments the group counter, moving to the next index in the ages list.
  4. Output:
    • The script will print the category (child, teenager, adult) for each age in the list along with the group number (index).

Python Exercise No. 2: The Number Guessing Game

Follow the following instructions to create this number guessing game:

  • Write a Python program that plays a number guessing game with the user.
  • The program will generate a random number between 1 and 100, and the user has to guess the number.
  • The user gets a maximum of 10 attempts.
  • After each guess, the program should tell the user if their guess was too high, too low, or correct.
  • If the user guesses correctly or runs out of attempts, the game ends.

Key Concepts: while loop, for loop, range, conditional statements, input(), random.randint().

Hint:

  • Your task is to create a game where the user needs to guess a randomly generated number between 1 and 100.
  • You’ll use a for loop with the range function to limit the number of guesses to 10.
  • Inside the loop, use input() to get the user’s guess and compare it with the generated number using conditional statements (if, elif, else).
  • Remember to convert the input from a string to an integer.
  • If the guess is correct or if 10 attempts are completed, the game should end.

Python Program (for Readers to Solve)

Python
import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Instructions for the user
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100. You have 10 tries to guess it.")

# Start a for loop with a range for 10 attempts
for attempt in range(1, 11):
    # Get user's guess using input() and convert it to an integer
    guess = int(input(f"Attempt {attempt} of 10 - Make a guess: "))

    # Write your conditional statements here to check if the guess is too low, too high, or correct.
    # ...

# Remember to add a way to end the game if the user guesses correctly or uses all attempts.

Solution to Python Exercise No. 2

Python
import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Instructions for the user
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100. You have 10 tries to guess it.")

# Start a for loop with a range for 10 attempts
for attempt in range(1, 11):
    # Get user's guess using input() and convert it to an integer
    guess = int(input(f"Attempt {attempt} of 10 - Make a guess: "))

    # Conditional statements to check if the guess is too low, too high, or correct
    if guess < secret_number:
        print("Your guess is too low.")
    elif guess > secret_number:
        print("Your guess is too high.")
    else:
        print(f"Congratulations! You guessed it right! The number was {secret_number}.")
        break
else:
    # This part executes if the loop wasn't broken, meaning the guess was never correct
    print(f"Sorry, you've used all your attempts. The number was {secret_number}.")

Explanation

  1. Guessing and Input Conversion: The user’s guess is taken via input() and converted to an integer since input() returns a string by default.
  2. Conditional Logic: The if, elif, and else statements compare the user’s guess with the secret_number.
    • If the guess is less than the secret_number, it prints that the guess is too low.
    • If the guess is greater, it indicates the guess is too high.
    • If the guess is equal to the secret_number, it congratulates the user and breaks out of the loop.
  3. Loop Completion: The else block attached to the for loop executes if the user fails to guess correctly within 10 attempts. It informs the user of the correct number.
  4. This solution encapsulates all the concepts we wanted to practice: for loops, the range function, conditional statements, and basic user input/output handling. It’s a fun and interactive way to get hands-on with Python! 🌟🐍

Conclusion

Loops are an essential tool in Python programming, allowing you to automate repetitive tasks efficiently.

Whether it’s iterating through items in a list with a for loop or repeatedly executing a block of code with a while loop, mastering these concepts is crucial for any budding programmer.

Remember, practice is key to understanding, so I encourage you to try writing your own loops to solidify your knowledge.

Happy coding!