Question

In: Computer Science

main() module Display "Welcome to my Guess the number program!" while true display_menu() Get input if(option==1)...

main() module

Display "Welcome to my Guess the number program!"

while true

display_menu()

Get input

if(option==1)

user_guess()

elif(option==2)

computer_guess()

else

break

user_guess() module

random mynumber

count=1

userGuesses=[]

while True

try

Display "Guess a number between 1 and 10"

Get guess

while guess<1 or guess>10

Display "Guess a number between 1 and 10"

Get guess

except

Display "numbers only"

continue

userGuesses.append(guess)

if (guess<mynumber)

Display "Too low"

count=count+1

else if (guess>mynumber)

Display "Too high"

count=count+1

else if (guess==mynumber)

Display "You guessed it in "+ count + " attempts"

Display "you picked the following numbers: " +userGuesses

computer_guess() module

Get number from user

count=1

computerGuesses=[]

while True

Get randomval from computer

computerGuesses.append(randomval)

if (number<randomval)

Display "Too low"

count=count+1

else if (number>randomval)

Display "Too high"

count=count+1

else if (number==randomval)

Display "The computer guessed it in "+ count + " attempts. The number was "+randomval

Display "The computer guessed the following numbers "+computerGuesses

else

break

When you run the program you should see the following:

Welcome to my Guess the number program!

  1. You guess the number
  2. You type a number and see if the computer can guess it
  3. Exit

What is your choice: 1

Please guess a number between 1 and 10: 5

Too high

Please guess a number between 1 and 10: 4

Too high

Please guess a number between 1 and 10: 3

Too high

Please guess a number between 1 and 10: 2

Too high

Please guess a number between 1 and 10: 1

You guessed it! It took you 5 attempts

You picked the following numbers: [5, 4, 3, 2, 1]

  1. You guess the number
  2. You type a number and see if the computer can guess it
  3. Exit

What is your choice: 2

Please enter a number between 1 and 10 for the computer to guess: 5

The computer guessed 8 which is too high

The computer guessed 7 which is too high

The computer guessed 4 which is too low

The computer guessed 7 which is too high

The computer guessed 4 which is too low

The computer guessed 7 which is too high

The computer guessed 2 which is too low

The computer guessed 1 which is too low

The computer guessed 7 which is too high

The computer guessed 6 which is too high

The computer guessed 3 which is too low

The computer guessed it! It took 12 attempts

The computer guessed the following numbers: [8, 7, 4, 7, 4, 7, 2, 1, 7, 6, 3, 5]

  1. You guess the number
  2. You type a number and see if the computer can guess it
  3. Exit

What is your choice: 3

Thank you for playing the guess the number game!

Be sure to submit your assignment

Don't forget this code so your program will start and call the main() function when you run it.

if __name__ == "__main__":
main();

Python Programming!

Solutions

Expert Solution

The Python 3 code for the " Guess the number" Game is:

# Importing random library to use a random function
import random

# user_choice() aks user to select a option from displayed options and returns choice
def user_choice():
    print("1 for You guess the number\n2 for You type a number and see if computer can guess it\n3 for exit")
    # Using try-except to handle exceptions
    # If user enters a input other than integer try-except handles exception
    try:
        choice1=int(input('Enter your choice: '))
    except Exception:
        print('Enter only integers 1, 2, 3!!!')
        return user_choice
    else:
        if(choice1>3 or choice1<1):
            user_choice()
        return choice1

# user_input() functions takes input from user
def user_input():
    # Using try-except to handle exceptions
    # If user enters a input other than integer try-except handles exception
    try:
        num = int(input('Enter your guess: '))
    except Exception:
        print('Only integers between 1 to 10 are accepted!!!')
        user_input()
    else:
        if(num>10 or num<1):
            print('Only integers between 1 to 10 are accepted!!!')
            return user_input
        return num

# comp_input() randomly generates a number in range (0,10)
def comp_input():
    c = random.randrange(1,10)
    return c

# user_guess() checks if the user entered numbers is equal to computer generated number
def user_guess():
    #generating a random number
    comp_number = random.randrange(1,10)
    # defining a list to add user guessed numbers
    inlist = []
    user_number = user_input()
    #using .append() function to add user guessed number to list
    inlist.append(user_number)
    count = 1
    # While loop repeats till user guess right number
    while(user_number!=comp_number):
        # if user_number>comp_number then printing guess too high
        # and taking user input again
        if user_number>comp_number:
            print("Your guess is too high")
            count = count+1;
            user_number=user_input()
            inlist.append(user_number)

        # if user_number<comp_number then printing guess too high
        # and taking user input again
        if user_number<comp_number:
            print("Your guess is too low")
            count =count+1
            user_number=user_input()
            inlist.append(user_number)
    
    # Completion of while loop indicates user guessed the right number
    print("You guessed it! It took you {}".format(count)+" attempts")
    print("You picked the numbers: {}".format(inlist))
    
# comp_guess() functionality is similar to user_guess() function
# Just computer and user variables are reversed
def comp_guess():
    inlist = []
    comp_number = comp_input()
    count = 1
    inlist.append(comp_number)
    user_number = int(input("Please enter a number between 1 and 10 for the computer to guess: "))
    while(comp_number!=user_number):
        if(comp_number>user_number):
            print('The computer guessed {}'.format(comp_number)+" which is too high")
            count =count +1
            comp_number = comp_input()
            inlist.append(comp_number)
        if(comp_number<user_number):
            print('The computer guessed {}'.format(comp_number)+" which is too low")
            count =count +1
            comp_number = comp_input()
            inlist.append(comp_number)
    print("The computer guessed it! It took {}".format(count)+" attempts")
    print("The computer guessed the numbers: {}".format(inlist))
    
 # main functions takes user choice and calls respective functions
def main():
    choice=0
    # while loop repeats till user decides to exit by selecting 3rd option
    while choice!=3:
        choice = user_choice()
        if choice==1:
            user_guess()
        elif choice==2:
            comp_guess()
        elif choice==3:
            print("Thank you for playing the guess the number game")
        else:
            print('Enter only integers 1, 2, 3!!!')
            choice = user_choice()


if __name__ == '__main__':
        main()

I have generated a random number for computer to guess in the range (1,10) using the random.randrange(1,10) by importing random library. This code handles all kinds of exceptions in taking user input. If a user inputs a string or char or float instead of an integer as input then try-except. Every time user guessed a number I added it to a list to diaplay the user guessed numbers at the end.

I have provided comment in the program explaining the lines of code. I have tested code for all possible cases and validated the code is working good. I am sharing few output screenshots for your reference.

Hope the answer helps you.

Thank you :)


Related Solutions

(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and...
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and a menu of options for the user to choose from. Welcome to the Email Analyzer program. Please choose from the following options: Upload text data Find by Receiver Download statistics Exit the program Program Options Option 1: Upload Text Data If the user chooses this option, the program will Prompt the user for the file that contains the data. Read in the records in...
Please add to this Python, Guess My Number Program. Add code to the program to make...
Please add to this Python, Guess My Number Program. Add code to the program to make it ask the user for his/her name and then greet that user by their name. Please add code comments throughout the rest of the program If possible or where you add in the code to make it ask the name and greet them before the program begins. import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the...
Write a program to prompt the user to display the following menu: Guess-Number                        Concat-names     &
Write a program to prompt the user to display the following menu: Guess-Number                        Concat-names             Quit If the user selects Guess-number, your program needs to call a user-defined function called int guess-number ( ). Use random number generator to generate a number between 1 – 100. Prompt the user to guess the generated number and print the following messages. Print the guessed number in main (): Guess a number: 76 96: Too large 10 Too small 70 Close Do you...
C++ PLEASE Write a program to prompt the user to display the following menu: Guess-Number                       ...
C++ PLEASE Write a program to prompt the user to display the following menu: Guess-Number                        Concat-names             Quit If the user selects Guess-number, your program needs to call a user-defined function called int guess-number ( ). Use random number generator to generate a number between 1 – 100. Prompt the user to guess the generated number and print the following messages. Print the guessed number in main (): Guess a number: 76 96: Too large 10 Too small 70 Close...
Number guessing Game (20 Marks) Write a C program that implements the “guess my number” game....
Number guessing Game Write a C program that implements the “guess my number” game. The computer chooses a random number using the following random generator function srand(time(NULL)); int r = rand() % 100 + 1; that creates a random number between 1 and 100 and puts it in the variable r. (Note that you have to include <time.h>) Then it asks the user to make a guess. Each time the user makes a guess, the program tells the user if...
Write a program that accept an integer input from the user and display the least number...
Write a program that accept an integer input from the user and display the least number of combinations of 500s, 100s, 50s, 20s, 10s, 5s, and 1s. Test your solution using this samples] a. Input: 250 Output: 1x200s, 1x50s b. Input: 1127 Output: 5x200s, 1x100s, 1x20s, 1x5s, 2x1s c. Input: 1127 Output: 5x200s, 1x100s, 1x20s, 1x5s, 2x1s d. Input: 19 Output: 1x10s, 1x5s, 4x1s ​[Hints] o Use division to determine the number of occurrence of each element (i.e. 200, 100)...
Part 1 Write a program that reads a line of input and display the characters between...
Part 1 Write a program that reads a line of input and display the characters between the first two '*' characters. If no two '*' occur, the program should display a message about not finding two * characters. For example, if the user enters: 1abc*D2Efg_#!*345Higkl*mn+op*qr the program should display the following: D2Efg_#! 1) Name your program stars.c. 2) Assume input is no more than 1000 characters. 3) String library functions are NOT allowed in this program. 4) To read a...
Write a C program that asks the user to guess a number between 1 and 15(1...
Write a C program that asks the user to guess a number between 1 and 15(1 and 15 are included). The user is given three trials. This is what I have so far. /* Nick Chioma COP 3223 - HW_2 */ #include <iostream> #include <time.h> // needed for time function #include <stdlib.h> // needed for srand, rand functions int main () {       int numbertoguess, num, correct, attempts;       srand(time(NULL)); //this initializes the random seed, making a new...
Create a PYTHON program that lets a user guess a number from 1 to 1,000: -i...
Create a PYTHON program that lets a user guess a number from 1 to 1,000: -i used random.randint(1,1000) -must give hints like (pick a lower/higher number) which i already did -tell the user when he has repeated a number (help) -the game only ends when you guess the number (help) -you loose $50 every failed attempt (done) ****I did it as a while loop -
y'=y-x^2 ; y(1)= -4 My MATLAB program won't work. I am trying to get the main...
y'=y-x^2 ; y(1)= -4 My MATLAB program won't work. I am trying to get the main program to output a plot of the three equations (1 from the main program and two called in the function). The goal is to code a Euler method and a 2nd order Taylor numerical solution for a. x0= 1.0 , step size h= 0.2, # of steps n=20 b. x0= 1.0 , step size h=0.05 , # of steps n=80 ; write a separate...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT