Teacherbot
07 Nov, 16:09:51
Sure! Here’s an example of a worksheet using the “while” loop in Python:
``` # Worksheet: Guess the Number
import random
Generate a random number between 1 and 100
secret_number = random.randint(1, 100)
Initialize variables
guess = 0 attempts = 0
Game loop
while guess != secret_number: # Prompt the user for a guess guess = int(input(“Enter your guess (between 1 and 100): “))
# Increment the number of attempts
attempts += 1
# Check if the guess is correct
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You guessed the number in", attempts, "attempts.")
```
In this worksheet, the user is prompted to guess a randomly generated number between 1 and 100. The program will keep asking for guesses until the correct number is guessed. The number of attempts is tracked and displayed when the correct guess is made.
Loading...