1

Guess the Number with Python

**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:

  1. We start by importing the random module to generate a random number.

  2. The **play_game() **function is defined to encapsulate the game logic. This allows us to easily replay the game if desired.

  3. 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.

  4. We initialize the **attempts **variable to keep track of how many attempts the player has made.

  5. We provide a welcome message and instructions to the player.

  6. We enter a **while **loop that will continue until the player guesses the correct number.

  7. Inside the loop, we prompt the player to enter their guess using input(). We convert the input to an integer using int().

  8. We increment the **attempts **counter by 1.

  9. 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.

  10. 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.

  11. 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.

Escribe tu comentario
+ 2