Guess The Number Code

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Here's a simple text-based guessing game in Python where the player has to guess a randomly

generated number between 1 and 100:

python

Copy code

import random

def guess_the_number():

# Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

print("Welcome to the Guess the Number game!")

print("I've picked a random number between 1 and 100. Try to guess it!")

# Keep track of the number of attempts

attempts = 0

while True:

# Ask the player to guess the number

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

# Increment the number of attempts

attempts += 1

# Check if the guess is correct

if guess == secret_number:

print(f"Congratulations! You've guessed the number in {attempts} attempts.")


break

elif guess < secret_number:

print("Too low! Try again.")

else:

print("Too high! Try again.")

# Start the game

guess_the_number()

This code generates a random number between 1 and 100 and asks the player to guess it. After

each guess, the program provides feedback if the guess is too high or too low. The game

continues until the player guesses the correct number.

You might also like