Answer:
Here is the Python program:
import random #to generate random numbers
def generateRandNo(): #function to generate random number
randNo = random.randint(1,100) #generates random number in range from 1 to 100
return randNo #returns the generated random number
def userInput(message = "Guess the number "): #to gets integer input from user and return the input number
userGuess = int(input(message)) #store the int type input from user in userGuess variable
return userGuess #returns the user input number
def compareNumbers(userGuess,randNo): #compares the user input with actual randomly generated number
if userGuess > randNo: # if user input is greater than actual number
return "The number is too high"
elif userGuess < randNo: #if user input is less than actual number
return "The number is too low"
else: #if user guess is correct
return "Correct"
def main(): #main method
correct = False #sets correct to False
begin = True #sets start game i.e. begin to True
while correct or begin: #while loop keeps repeating as long as user guess is correct or user wants to start game again
guessCount = 0 #counts number of trials user takes to guess the correct number
randNo = generateRandNo() #generates a random number using generateRandNo
userGuess = userInput() #gets input number from user using userInput method
guessCount+=1 #increments at each guess made by user
message = compareNumbers(userGuess,randNo) #compares user guess input number with actual number
while message != "Correct" : # while message is not equal to Correct
print(message) #prints to guess the number
userGuess = userInput("Try again: ") #keeps asking user to try again and enter a number
guessCount = guessCount + 1 #increments guessCount by 1 at each guess made by user
message = compareNumbers(userGuess,randNo) #compares user input with actual number
print()
print(message,"It took you ",guessCount," attempts to answer\\") #prints how much trials user took to guess correct number
choice = input("Do you wish to continue? (Enter yes or no) ") #asks user if user wants to start over
if choice == 'no': # if user enters no
exit(1) #exits the program
else: #if user enters yes starts the game again
correct = True #sets correct guess to True
main() #calls main method to start the guess game
Step-by-step explanation:
The program is well explained in the comments attached with each line of the code. Suppose the randomly generated number (actual number) is 50 and user input is 24 then message The number is too low is displayed and if user guess input is 80 then The number is too high is displayed. If the user guesses the correct number i.e. 50 3rd time then the message displayed is:
It took you 3 attempts to answer.
The the user is asked to continue as:
Do you wish to continue? (Enter yes or no)
If user enters no the program exits if yes then user is asked to Guess the number again.
The screenshot of output is attached.