Guessing Game
Guessing Game
Description :
This is a Python program that creates a guessing game where the player tries to guess a
randomly generated number between 1 and 100.
The program starts by importing the random module to generate a random integer
between 1 and 100.
Next, the program defines a custom exception Notvalid which is raised when the user
enters a number that is not between 1 and 100.
After that, the program defines a GuessingGame class that has an __init__ method which
initializes the randomly generated number and the number of guesses to 0.
The GuessingGame class also has a guess method that takes a number as an argument and
returns a string based on whether the number is higher or lower than the randomly
generated number. If the number is within 5 of the randomly generated number, the string
returned will be "Little high" or "Little low". If the number is further away, the string
returned will be "Too high" or "Too low". If the number is equal to the randomly generated
number, the string returned will be "Correct!".
Finally, the program creates an instance of the GuessingGame class and starts a loop
where the user is prompted to guess the number. If the user enters a number that is not
between 1 and 100, the program raises the Notvalid exception. If the user guesses the
correct number, the program prints a congratulatory message and the number of guesses it
took to guess the correct number.
Code:
import random
class Notvalid(Exception):
pass
class GuessingGame:
def __init__(self):
self.guesses = 0
self.guesses += 1
if(number<0 or number>100):
else:
if(number>self.number-5):
else:
if(number<self.number+5):
else:
else:
return "Correct!"
game = GuessingGame()
print("I'm thinking of a number between 1 and 100. Can you guess it?")
while True:
try:
result = game.guess(guess)
print(result)
if result == "Correct!":
break
except Notvalid as n:
print("Notvalid :",n)
Output :