Description of the problem - Create a game in which the computer randomly chooses a number in a range and the user has to guess this number.
If the user typed 1 then the user has chosen to play at an easy level and the computer should randomly select the number between 1 and 100.
If the user types a number it will be converted from string to integer. and assigned to the variable named USER_INPUT. The execution of the program jumps to line 9 of the previously shown code block. If the USER_INPUT value is greater than the NUMBER which is randomly selected then the computer will display a message stating that your number (the number that the user entered ) i.e. "Your number is greater than the number chosen by the computer."
If the USER_INPUT value is equal to the NUMBER value that the following output will be shown:
Output:
The main menu function will show as output the following options New game (type: 1) and Quit game (type: 2). The user has to type one of the previously mentioned numbers and the value will be converted to an integer which will be assigned to a variable named OPTION. The output of the main menu function is OPTION.
Solution: Beginner Level
This game requires the use of one library and that is random library. To import this library simply type:import randomThe function randint is required from random library to select random integer from specific range. The execution program will start by showing the main menu of the game. This is a simple menu that consists of two options i.e. New game and Quit the game. This menu will be created using one while loop with try-except blocks. In the try block, the previously mentioned options will be shown and the user has to choose between New Game and the Quit Game option by typing numbers 1 or 2, respectively. If of course, the input is not 1 or 2 i.e. integer higher than 2 the program will be terminated, but more on that later. On the other hand if instead of a number the user types the character from the keyboard the program will jump from the try block to the except block since Python will raise the ValueError and display a message "Invalid input. Please try again.", and program will return to the try block.
while True:In case the user types an integer value 1 or 2 the program will skip this while loop and jump to the next line of code. In case the user typed 1 then the number 1 is assigned to the OPTION variable. If the value of the OPTION variable is equal to 1 then the user must choose the difficulty. In this program, the difficulty is represented by the size of the range of numbers from which the computer chooses numbers. The higher the range the more difficult is to guess the number. Here three levels of difficulty are defined and these are:
try:
print("#######################################")
print("#### Guess the number #################")
print("#######################################")
print("## Please choose an option ############")
print("## 1. New Game (type: 1) ##############")
print("## 2. Quit Game (type: 2) #############")
print("#######################################")
OPTION = int(input("Choose an option:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
- Easy (range 0 to 100) - at easy level range of numbers from which computer can randomly choose a number is from 0 to 100,
- Medium (range 0 to 10000) - at the medium level difficulty the range of numbers from which the computer can randomly choose a number is from 0 to 10000.
- Hard (range 0 to 1000000) - at this level the range of numbers from which a computer can randomly choose a number is from 0 to 1000000.
if OPTION == 1:If of course, the user types a character that Python cannot convert to an integer then the exception block activates due to Python raising the ValueError. Instead on the screen output will be shown stating "Invalid input. Please try again.".
while True:
try:
print("#############################################")
print("########### Select Difficulty ###############")
print("## 1. Easy (range 0 to 100), type: 1 ########")
print("## 2. Medium (range 0 to 10000), type:2 #####")
print("## 3. Hard (range 0 to 1000000), type: 3 ####")
print("#############################################")
DIFFICULTY = int(input("Choose a difficulty:> "))
break
except ValueError:
print("Invalid input. Please try again.)
continue
If the user typed 1 then the user has chosen to play at an easy level and the computer should randomly select the number between 1 and 100.
if DIFFICULTY == 1:If the user typed 2 then the user has chosen to play and medium level and the computer should randomly select the number between 1 and 1000.
NUMBER = random.randint(0,100)
elif DIFFICULTY == 2:Finally, if the user typed 3 then the user has chosen hard difficulty and the computer should randomly select the number between 1 and 1000000.
NUMBER = random.randint(0,10000)
elif DIFFICULTY == 3:The next step is to enable the user to guess the number and to see if the entered number by the user is greater or lower than the number randomly selected from a predefined range. This will be done using a while loop and this loop will be exited when the user guesses the number. The entire while loop is shown below.
NUMBER = random.randint(0,1000000)
while True:So, the previous block of code starts by asking the user to type in a number, preferably an integer. However, the character cannot be written since it causes ValueError. This error is raised when we are trying to convert string to integer (It cannot be done!!). By using the except block we are avoiding the error and instead, the execution program continues by displaying the string "Invalid input. Please try again! and after that, the execution of the program jumps to the try block and the output is shown "Enter a number:> "
while True:
try:
USER_INPUT = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input. Please try again!")
continue
if USER_INPUT > NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is greater than the number chosen by the computer.")
continue
elif USER_INPUT == NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is equal to the number chosen by the computer.")
break
else:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is lower than the number chosen by the computer")
continue
If the user types a number it will be converted from string to integer. and assigned to the variable named USER_INPUT. The execution of the program jumps to line 9 of the previously shown code block. If the USER_INPUT value is greater than the NUMBER which is randomly selected then the computer will display a message stating that your number (the number that the user entered ) i.e. "Your number is greater than the number chosen by the computer."
If the USER_INPUT value is equal to the NUMBER value that the following output will be shown:
- "You have entered number {}". - instead of {} the USER_INPUT number will be inserted using the format built-in function.
- "Your number is equal to the number chosen by the computer."
- break - statement will terminate the loop which contains this command.
- "You have entered number {}" - instead of {} the USER_INPUT value will be inserted using format built-in function.
- "Your number is lower than the number chosen by the computer."
- continue - this code line is not mandatory since the role of the continue statement is to skip the rest of the code inside a loop for the current iteration only. Since there is no code below the continue function this command is not necessary.
elif OPTION >= 2:The solution (beginner level) to the entire Guess the number game is given below.
print("You have exited the game!")
import random
while True:
try:
print("#######################################")
print("#### Guess the number #################")
print("#######################################")
print("## Please choose an option ############")
print("## 1. New Game (type: 1) ##############")
print("## 2. Quit Game (type: 2) #############")
print("#######################################")
OPTION = int(input("Choose an option:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
if OPTION == 1:
while True:
try:
print("#############################################")
print("## Select Difficulty ########################")
print("## 1. Easy (range 0 to 100), type: 1 ########")
print("## 2. Medium (range 0 to 10000), type:2 #####")
print("## 3. Hard (range 0 to 1000000), type: 3 ####")
print("#############################################")
DIFFICULTY = int(input("Choose a difficulty:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
if DIFFICULTY == 1:
NUMBER = random.randint(0,100)
elif DIFFICULTY == 2:
NUMBER = random.randint(0,10000)
elif DIFFICULTY == 3:
NUMBER = random.randint(0,1000000)
while True:
while True:
try:
USER_INPUT = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input. Please try again!")
continue
if USER_INPUT > NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is greater than the number chosen by the computer.")
continue
elif USER_INPUT == NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is equal to the number chosen by the computer.")
break
else:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is lower than the number chosen by the computer")
continue
elif OPTION >= 2:
print("You have exited the game!")
Output:
#######################################
#### Guess the number #################
#######################################
## Please choose an option ############
## 1. New Game (type: 1) ##############
## 2. Quit Game (type: 2) #############
#######################################
Choose an option:> 1
#############################################
## Select Difficulty ########################
## 1. Easy (range 0 to 100), type: 1 ########
## 2. Medium (range 0 to 10000), type:2 #####
## 3. Hard (range 0 to 1000000), type: 3 ####
#############################################
Choose a difficulty:> 1
Enter a number:> 50
You have entered number 50.
Your number is lower than the number chosen by the computer
Enter a number:> 80
You have entered number 80.
Your number is greater than the number chosen by the computer.
Enter a number:> 40
You have entered number 40.
Your number is lower than the number chosen by the computer
Enter a number:> 50
You have entered number 50.
Your number is lower than the number chosen by the computer
Enter a number:> 60
You have entered number 60.
Your number is lower than the number chosen by the computer
Enter a number:> 70
You have entered number 70.
Your number is lower than the number chosen by the computer
Enter a number:> 75
You have entered number 75.
Your number is lower than the number chosen by the computer
Enter a number:> 76
You have entered number 76.
Your number is equal to the number chosen by the computer.
Solution: Intermediate Level
At the intermediate level, we will use functions so the entire code written previously will be based on functions. After all, functions were defined we will create one while loop in which these functions will be called and executed. The previous program will be divided into the main menu, game difficulty, and game functions that will be executed inside a while loop.The main menu function will show as output the following options New game (type: 1) and Quit game (type: 2). The user has to type one of the previously mentioned numbers and the value will be converted to an integer which will be assigned to a variable named OPTION. The output of the main menu function is OPTION.
def MainMenu():The next function is named the game difficulty and as the name states with this function, you can choose the game difficulty. Functions start by displaying three types of difficulties i.e. Easy (range from 0 to 100), Medium (range from 0 to 10000), and Hard (0 to 1000000). Easy mode type 1, medium type 2, and Hard mode type 3. The value entered by the user is converted to an integer and assigned to a variable named DIFFICULTY. If DIFFICULTY is equal to 1 then the random integer will be chosen in the range from 0 to 100. IF DIFFICULTY is equal to 2 then the random integer will be chosen in the range from 0 to 10000 and assigned to the variable named NUMBER. If the DIFFICULTY is equal to 3 then the random integer will be chosen in the range from 0 to 1000000 and assigned to the variable named NUMBER.
while True:
try:
print("#######################################")
print("#### Guess the number #################")
print("#######################################")
print("## Please choose an option ############")
print("## 1. New Game (type: 1) ##############")
print("## 2. Quit Game (type: 2) #############")
print("#######################################")
OPTION = int(input("Choose an option:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
return OPTION
def GameDifficulty():The final function that must be defined is the function called Game, and this function requires only one argument i.e. the output of the GameDifficulty function. The game functions start by asking a user to type a number. This number is converted to an integer if possible. If the input cannot be converted to an integer then the user will have to repeat the process of entering a number. In further steps, the USER_INPUT in which the user input number is stored is compared to the number (the randomly chosen number for the predefined range in which the correct value is not known). If the USER_INPUT is greater than the NUMBER then the strings will be displayed i.e. Your number is greater than the number chosen by the computer, and the user will have to enter a new number again. If the USER_INPUT is equal to NUMBER then the execution of the program is terminated since we have guessed the number. Finally, if the user input is less than the number randomly chosen by the computer then the user will have to type again a new number since the current number is less than the number randomly chosen by the computer.
while True:
try:
print("#############################################")
print("## Select Difficulty ########################")
print("## 1. Easy (range 0 to 100), type: 1 ########")
print("## 2. Medium (range 0 to 10000), type:2 #####")
print("## 3. Hard (range 0 to 1000000), type: 3 ####")
print("#############################################")
DIFFICULTY = int(input("Choose a difficulty:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
if DIFFICULTY == 1:
NUMBER = random.randint(0,100)
elif DIFFICULTY == 2:
NUMBER = random.randint(0,10000)
elif DIFFICULTY == 3:
NUMBER = random.randint(0,1000000)
return NUMBER
def Game(NUMBER):Finally, all these functions will be used inside the while loop. The while loop will start by calling the MainMenu function and storing its value to the start variable name. Id start equals 1 then the GameDifficulty() function will be called and the return value is stored at a variable named number. The next step is to call the function Game(number) and provide this function with a number argument. If the value of the USER INPUT is 2 or greater than 2 the program will be terminated the string "Your number is lower than the number chosen by the computer" will be displayed. The entire code for the guessing number game at the intermediate level is given below.
while True:
while True:
try:
USER_INPUT = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input. Please try again!")
continue
if USER_INPUT > NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is greater than the number chosen by the computer.")
continue
elif USER_INPUT == NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is equal to the number chosen by the computer.")
break
else:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is lower than the number chosen by the computer")
continue
while True:
start = MainMenu()
if start == 1:
number = GameDifficulty()
execution = Game(number)
continue
elif start >= 2:
print("You have exited the game!")
break
def MainMenu():The example output is shown below.
while True:
try:
print("#######################################")
print("#### Guess the number #################")
print("#######################################")
print("## Please choose an option ############")
print("## 1. New Game (type: 1) ##############")
print("## 2. Quit Game (type: 2) #############")
print("#######################################")
OPTION = int(input("Choose an option:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
return OPTION
def GameDifficulty():
while True:
try:
print("#############################################")
print("## Select Difficulty ########################")
print("## 1. Easy (range 0 to 100), type: 1 ########")
print("## 2. Medium (range 0 to 10000), type:2 #####")
print("## 3. Hard (range 0 to 1000000), type: 3 ####")
print("#############################################")
DIFFICULTY = int(input("Choose a difficulty:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
if DIFFICULTY == 1:
NUMBER = random.randint(0,100)
elif DIFFICULTY == 2:
NUMBER = random.randint(0,10000)
elif DIFFICULTY == 3:
NUMBER = random.randint(0,1000000)
return NUMBER
def Game(NUMBER):
while True:
while True:
try:
USER_INPUT = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input. Please try again!")
continue
if USER_INPUT > NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is greater than the number chosen by the computer.")
continue
elif USER_INPUT == NUMBER:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is equal to the number chosen by the computer.")
break
else:
print("You have entered number {}.".format(USER_INPUT))
print("Your number is lower than the number chosen by the computer")
continue
while True:
start = MainMenu()
if start == 1:
number = GameDifficulty()
execution = Game(number)
continue
elif start >= 2:
print("You have exited the game!")
break
#######################################
#### Guess the number #################
#######################################
## Please choose an option ############
## 1. New Game (type: 1) ##############
## 2. Quit Game (type: 2) #############
#######################################
Choose an option:> 1
#############################################
## Select Difficulty ########################
## 1. Easy (range 0 to 100), type: 1 ########
## 2. Medium (range 0 to 10000), type:2 #####
## 3. Hard (range 0 to 1000000), type: 3 ####
#############################################
Choose a difficulty:> 1
Enter a number:> 90
You have entered number 90.
Your number is greater than the number chosen by the computer.
Enter a number:> 20
You have entered number 20.
Your number is lower than the number chosen by the computer
Enter a number:> 50
You have entered number 50.
Your number is greater than the number chosen by the computer.
Enter a number:> 30
You have entered number 30.
Your number is lower than the number chosen by the computer
Enter a number:> 40
You have entered number 40.
Your number is greater than the number chosen by the computer.
Enter a number:> 35
You have entered number 35.
Your number is lower than the number chosen by the computer
Enter a number:> 36
You have entered number 36.
Your number is equal to the number chosen by the computer.
#######################################
#### Guess the number #################
#######################################
## Please choose an option ############
## 1. New Game (type: 1) ##############
## 2. Quit Game (type: 2) #############
#######################################
Choose an option:> 2
You have exited the game!
Solution: Advanced Level
At the advanced level, we will introduce object-oriented programming i.e. the entire program will fit inside one class called GuessNumber. This class consists of three methods and these are MainMenu, GameDifficulty, Game. Outside the class, the object test is created as an instance of the class GuessNumber. After the object creation, the while loop is created in which all three methods were used. The output of the MainMenu() method is assigned to the variable name Option. If the Option is equal to 1 the other two methods are used GameDifficulty() and Game() method. The output value of the GameDifficulty() method is assigned to the Number variable which is used as the argument of the Game(Number) method. On the other hand, if the value of the Option variable is greater or equal to 2 the string "You have exited the game. Goodbye!" will be displayed and the program will be terminated. The entire code at the advanced level is given below.class GuessNumber():The example output with Easy difficulty is given below.
def MainMenu(self):
while True:
try:
print("#######################################")
print("#### Guess the number #################")
print("#######################################")
print("## Please choose an option ############")
print("## 1. New Game (type: 1) ##############")
print("## 2. Quit Game (type: 2) #############")
print("#######################################")
self.OPTION = int(input("Choose an option:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
return self.OPTION
def GameDifficulty(self):
while True:
try:
print("#############################################")
print("## Select Difficulty ########################")
print("## 1. Easy (range 0 to 100), type: 1 ########")
print("## 2. Medium (range 0 to 10000), type:2 #####")
print("## 3. Hard (range 0 to 1000000), type: 3 ####")
print("#############################################")
self.DIFFICULTY = int(input("Choose a difficulty:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
if self.DIFFICULTY == 1:
self.NUMBER = random.randint(0,100)
elif self.DIFFICULTY == 2:
self.NUMBER = random.randint(0,10000)
elif self.DIFFICULTY == 3:
self.NUMBER = random.randint(0,1000000)
return self.NUMBER
def Game(self, NUMBER):
while True:
while True:
try:
self.USER_INPUT = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input. Please try again!")
continue
if self.USER_INPUT > self.NUMBER:
print("You have entered number {}.".format(self.USER_INPUT))
print("Your number is greater than the number chosen by the computer.")
continue
elif self.USER_INPUT == self.NUMBER:
print("You have entered number {}.".format(self.USER_INPUT))
print("Your number is equal to the number chosen by the computer.")
break
else:
print("You have entered number {}.".format(self.USER_INPUT))
print("Your number is lower than the number chosen by the computer")
continue
test = GuesNumber()
while True:
Option = test.MainMenu()
if Option == 1:
Number = test.GameDifficulty()
test.Game(Number)
continue
elif Option >= 2: print("You have exited the game. Goodbye!")
break
#######################################
#### Guess the number #################
#######################################
## Please choose an option ############
## 1. New Game (type: 1) ##############
## 2. Quit Game (type: 2) #############
#######################################
Choose an option:> 1
#############################################
## Select Difficulty ########################
## 1. Easy (range 0 to 100), type: 1 ########
## 2. Medium (range 0 to 10000), type:2 #####
## 3. Hard (range 0 to 1000000), type: 3 ####
#############################################
Choose a difficulty:> 1
Enter a number:> 20
You have entered number 20.
Your number is lower than the number chosen by the computer
Enter a number:> 30
You have entered number 30.
Your number is greater than the number chosen by the computer.
Enter a number:> 25
You have entered number 25.
Your number is lower than the number chosen by the computer
Enter a number:> 26
You have entered number 26.
Your number is lower than the number chosen by the computer
Enter a number:> 28
You have entered number 28.
Your number is lower than the number chosen by the computer
Enter a number:> 29
You have entered number 29.
Your number is equal to the number chosen by the computer.
#######################################
#### Guess the number #################
#######################################
## Please choose an option ############
## 1. New Game (type: 1) ##############
## 2. Quit Game (type: 2) #############
#######################################
Choose an option:> 2
You have exited the game. Goodbye!