Here’s a simple Python script for a Number Guessing Game:
pythonCopy codeimport random
def number_guessing_game():
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Randomly select a number between 1 and 100
secret_number = random.randint(1, 100)
attempts = 0
while True:
# Get the player's guess
guess = int(input("Enter your guess: "))
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(f"Congratulations! You guessed the number in {attempts} attempts.")
break
if __name__ == "__main__":
number_guessing_game()
How it works:
- random.randint(1, 100): This function generates a random number between 1 and 100, which the player needs to guess.
- attempts: A counter that tracks how many guesses the player has made.
- while True: The loop continues until the player guesses the correct number.
- if-elif-else: The program provides feedback if the player’s guess is too low, too high, or correct.
To play:
- Run the script.
- Enter your guess when prompted.
- The game will continue until you guess the correct number, with hints provided after each guess.
Leave a Comment