Advertisement
CodeCrusader

Number Guessing Game

Jun 10th, 2023
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | Source Code | 0 0
  1. import random
  2.  
  3. def guess_number():
  4.     secret_number = random.randint(1, 100)
  5.     attempts = 0
  6.  
  7.     print("Welcome to the Number Guessing Game!")
  8.     print("I'm thinking of a number between 1 and 100.")
  9.     print("You have 10 attempts to guess the number.")
  10.  
  11.     while attempts < 10:
  12.         try:
  13.             guess = int(input("Take a guess: "))
  14.         except ValueError:
  15.             print("Invalid input. Please enter a valid integer.")
  16.             continue
  17.  
  18.         attempts += 1
  19.  
  20.         if guess < secret_number:
  21.             print("Too low! Try again.")
  22.         elif guess > secret_number:
  23.             print("Too high! Try again.")
  24.         else:
  25.             print(f"Congratulations! You guessed the number in {attempts} attempts!")
  26.             return
  27.  
  28.     print(f"Game over! The number was {secret_number}. Better luck next time!")
  29.  
  30. guess_number()
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement