**Guess the Number with Python **
import random
defplay_game():
secret_number = random.randint(1, 100)
attempts = 0
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
whileTrue:
guess = int(input("Take a guess: "))
attempts += 1if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts!")
break
play_game()
Let’s go through the code step by step:
We start by importing the random module to generate a random number.
The **play_game() **function is defined to encapsulate the game logic. This allows us to easily replay the game if desired.
Within the **play_game() **function, we use random.randint(1, 100) to generate a random number between 1 and 100, inclusive. This becomes the **secret_number **that the player needs to guess.
We initialize the **attempts **variable to keep track of how many attempts the player has made.
We provide a welcome message and instructions to the player.
We enter a **while **loop that will continue until the player guesses the correct number.
Inside the loop, we prompt the player to enter their guess using input(). We convert the input to an integer using int().
We increment the **attempts **counter by 1.
We compare the player’s guess to the secret_number. If the guess is lower than the secret number, we provide feedback to the player that the guess is too low. If the guess is higher, we inform the player that the guess is too high.
If the guess matches the secret_number, we congratulate the player and display the number of attempts it took. We then use **break **to exit the **while **loop.
Finally, we call the play_game() function to start the game.
To play the game, the player repeatedly enters guesses until they guess the correct number. The program provides feedback after each guess, indicating whether the guess is too high or too low. Once the correct number is guessed, the program displays the number of attempts taken.