quhluh icon

Guess Game

quhluh | 12/09/23 03:56:28 PM UTC | 0 ⭐ | 1271 👁️ | Never ⏰ | []
Python |

1.21 KB

|

None

|

0 👍

/

0 👎

import random
 
def guess_the_number():
    print("Welcome to Guess the Number!")
    print("I'm thinking of a number between 1 and 100.")
 
    # Generate a random number between 1 and 100
    secret_number = random.randint(1, 100)
 
    attempts = 0
 
    while True:
        try:
            # Get the player's guess
            guess = int(input("Enter your guess: "))
            attempts += 1
 
            # Check if the guess is correct
            if guess == secret_number:
                print(f"Congratulations! You guessed the number in {attempts} attempts.")
                break
            elif guess < secret_number:
                print("Too low! Try again.")
            else:
                print("Too high! Try again.")
 
        except ValueError:
            print("Invalid input. Please enter a valid number.")
 
if __name__ == "__main__":
    guess_the_number()
Copy and paste this code into a Python file (e.g., guess_the_number.py) and run it. This simple game asks the player to guess a randomly generated number between 1 and 100. The game provides feedback on whether the guess is too high, too low, or correct. The game continues until the player correctly guesses the number.

Comments