Advertisement
SkidScripts

Number guessing game code (python)

Nov 29th, 2023 (edited)
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. import random
  2.  
  3. def number_guessing_game():
  4.     print("Welcome to the Number Guessing Game!")
  5.     print("I'm thinking of a number between 1 and 100. Can you guess it?")
  6.    
  7.     # Generate a random number between 1 and 100
  8.     secret_number = random.randint(1, 100)
  9.    
  10.     attempts = 0
  11.     while True:
  12.         try:
  13.             guess = int(input("Enter your guess (between 1 and 100): "))
  14.             attempts += 1
  15.            
  16.             if guess < secret_number:
  17.                 print("Too low! Try a higher number.")
  18.             elif guess > secret_number:
  19.                 print("Too high! Try a lower number.")
  20.             else:
  21.                 print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!")
  22.                 break  # Exit the loop when the correct number is guessed
  23.         except ValueError:
  24.             print("Invalid input! Please enter a valid number.")
  25.  
  26. if __name__ == "__main__":
  27.     number_guessing_game()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement