You are on page 1of 3

Certainly!

A laboratory activity involving the use of `while` and `if` statements can be designed to help
students practice and understand the concepts of looping and conditional statements in programming.
Below is an example activity in the context of a simple Python program:

### Laboratory Activity: Guess the Number Game

#### Objective:

- Practice using `while` loops and `if` statements in Python.

#### Instructions:

1. **Introduction:**

- Explain the concept of `while` loops and `if` statements.

- Briefly discuss the idea of a simple guessing game.

2. **Task Description:**

- Ask students to create a Python program for a "Guess the Number" game.

- The computer will generate a random number between 1 and 100.

- The player has to guess the number.

- Provide feedback to the player if their guess is too high or too low.

- The game should continue until the player correctly guesses the number.

3. **Requirements:**

- Use a `while` loop to repeatedly prompt the user for guesses.

- Use an `if` statement to check if the guess is correct or not.

- Provide appropriate feedback to the player after each guess.

- End the game when the correct number is guessed.

- Optional: Add a limit to the number of attempts.


4. **Sample Code:**

```python

import random

# Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

# Set the maximum number of attempts

max_attempts = 10

attempts = 0

# Game loop

while attempts < max_attempts:

# Get the player's guess

guess = int(input("Enter your guess: "))

# Check if the guess is correct

if guess == secret_number:

print("Congratulations! You guessed the correct number.")

break

elif guess < secret_number:

print("Too low! Try again.")

else:

print("Too high! Try again.")

# Increment the attempts

attempts += 1

# Inform the player if they have run out of attempts


if attempts == max_attempts:

print(f"Sorry, you've run out of attempts. The correct number was {secret_number}.")

```

5. **Discussion:**

- Discuss the use of `while` loops for continuous gameplay.

- Review how `if` statements are used to check conditions.

- Explore how the game flow changes based on the user's input.

6. **Extensions (Optional):**

- Allow the player to play again.

- Implement input validation to handle non-numeric inputs.

- Customize the game further based on the class's programming proficiency.

Encourage students to run the program, test different scenarios, and modify the code to enhance their
understanding of `while` and `if` statements in Python.

You might also like