Question

In: Computer Science

Can you please see what I have done wrong with my program code and explain, This...

Can you please see what I have done wrong with my program code and explain, This python program is a guess my number program. I can not figure out what I have done wrong. When you enter a letter into the program, its supposed to say "Numbers Only" as a response. I can not seem to figure it out.. instead of an error message.

import random

def menu():
print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit")
while True:
c=int(input("Enter your choice: "))
if(c>=1 and c<=3):
return c
else:
print("Enter number between 1 and 3 inclusive.")

def guessingGame():
min_number=1
max_number=10
#set number of guesses = 0
numGuesses=0
rand=random.randint(min_number, max_number)
#prints the header, welcoming the user
print("\nWelcome to the Guess My Number Program!")
#While loop, comparing the users guessed number with the random number.
#If it matches, it will say you guessed it.
while (True):
#use try-block
try:
guess=eval(input("Please try to guess my number between 1 and 10:"))
#check if the guess is less than 0, then continye to beginning of the loop
if(guess<0):
continue;
elif (guess==rand):
#increment the guess count by 1
numGuesses=numGuesses+1
print("You guessed it! It took you ", numGuesses,"attempts")
#break will end the loop once the guess is a match.
#Conditions if the guess is too low or too high to keep guessing
break
elif(guess < rand):
#increment the guess count by 1
numGuesses = numGuesses +1
print("Too low")
else:
#increment the guess count by 1
numGuesses = numGuesses + 1
print("Too high")
except:
#print exception
print("Numbers only!")

def guessingGameComp():
countGuess=0
userNumber=int(input("\nPlease enter a number between 1 and 10 for the computer to guess:"))
while userNumber<1 or userNumber>10:
userNumber=int(input("Guess a number between 1 and 10: "))
while True:
countGuess+=1
compRand = random.randint(1,10)
if(userNumber==compRand):
print("The computer guessed it! It took {} attempts".format(countGuess))
break
elif(userNumber<compRand):
print("The computer guessed {} which is too low".format(compRand))
else:
print("The computer guessed {} which is too high".format(compRand))

def main():
while True:
userChoice=menu()
if userChoice==1:
guessingGame()
elif userChoice==2:
guessingGameComp()
elif userChoice==3:
print("\nThank you for playing the guess the number game!")
break
else:
print("Invalid choice!!!")

main()

Solutions

Expert Solution

#Python program for guessing game with user menu options.
#The corrections are shown in bold letters 
#intendations must be followed in the python program.
import random
def menu():
    print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit")
    while True:
        #Correction1:
        #Using try-except for the choice will handle the non-numbers 
        #If user enters alphabets, then except will show the message, "Numbers only!"
        try:
            c=int(input("Enter your choice: "))
            if(c>=1 and c<=3):
                return c
            else:
                print("Enter number between 1 and 3 inclusive.")
        except:
            # print exception
            print("Numbers only!")

def guessingGame():
    min_number=1
    max_number=10
    #set number of guesses = 0
    numGuesses=0
    rand=random.randint(min_number, max_number)
    #prints the header, welcoming the user
    print("\nWelcome to the Guess My Number Program!")
    #While loop, comparing the users guessed number with the random number.
    #If it matches, it will say you guessed it.
    while (True):
    #use try-block
        try:
            guess=eval(input("Please try to guess my number between 1 and 10:"))
            #check if the guess is less than 0, then continye to beginning of the loop
            if(guess<0):
                continue;
            elif (guess==rand):
                #increment the guess count by 1
                numGuesses=numGuesses+1
                print("You guessed it! It took you ", numGuesses,"attempts")
                #break will end the loop once the guess is a match.
                #Conditions if the guess is too low or too high to keep guessing
                break
            elif(guess < rand):
                #increment the guess count by 1
                numGuesses = numGuesses +1
                print("Too low")
            else:
                #increment the guess count by 1
                numGuesses = numGuesses + 1
                print("Too high")
        except:
            #print exception
            print("Numbers only!")

def guessingGameComp():
    
    countGuess=0
    userNumber=int(input("\nPlease enter a number between 1 and 10 for the computer to guess:"))
    
    while userNumber<1 or userNumber>10:
        userNumber=int(input("Guess a number between 1 and 10: "))

    while True:
        countGuess+=1
        compRand = random.randint(1,10)
        if(userNumber==compRand):
            print("The computer guessed it! It took {} attempts".format(countGuess))
            break
        elif(userNumber<compRand):
            print("The computer guessed {} which is too low".format(compRand))
        else:
            print("The computer guessed {} which is too high".format(compRand))

def main():
    while True:
        userChoice=menu()
        if userChoice==1:
            guessingGame()
        elif userChoice==2:
            guessingGameComp()
        elif userChoice==3:
            print("\nThank you for playing the guess the number game!")
            break
        else:
            print("Invalid choice!!!")

#calling main method to start the program
main()

------------------------------------------------------------------------------------------

Screen-shots with indentations

Sample Output:

1. You guess the number
2. You type a number and see if the computer can guess it
3. Exit
Enter your choice: a
Numbers only!
Enter your choice: 1

Welcome to the Guess My Number Program!
Please try to guess my number between 1 and 10:5
Too low
Please try to guess my number between 1 and 10:6
Too low
Please try to guess my number between 1 and 10:7
You guessed it! It took you 3 attempts


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

Please enter a number between 1 and 10 for the computer to guess:9
The computer guessed 5 which is too high
The computer guessed 2 which is too high
The computer guessed it! It took 3 attempts


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

Thank you for playing the guess the number game!


Related Solutions

I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
I am getting 7 errors can someone fix and explain what I did wrong. My code...
I am getting 7 errors can someone fix and explain what I did wrong. My code is at the bottom. Welcome to the DeVry Bank Automated Teller Machine Check balance Make withdrawal Make deposit View account information View statement View bank information Exit          The result of choosing #1 will be the following:           Current balance is: $2439.45     The result of choosing #2 will be the following:           How much would you like to withdraw? $200.50      The...
Please see if you can correct my code. I am getting an ReferenceError in Windows Powershell...
Please see if you can correct my code. I am getting an ReferenceError in Windows Powershell that says payment is undefined. I am trying to create a main.js file that imports the function from the hr.js file; call the function passing the necessary arguments and log the result to the console. main.js var Dev = require("./hr.js") const { add } = require("./hr.js") var dev_type = 1; var hr = 40; console.log("your weekly payment is " + payment(dev_type, hr)) dev_type =...
Can you please check my answers and if I am wrong correct me. Thank you! A....
Can you please check my answers and if I am wrong correct me. Thank you! A. In today's interconnected world, many central banks communicate regularly and frequently with the public about the state of the economy, the economic outlook, and the likely future course of monetary policy. Communication about the likely future course of monetary policy is known as "forward guidance.". If the central bank increases the reserve ratio, as the market has perfectly expected, which of the following will...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
I have this mystery code. I dont know what the code does. Can somone please explain...
I have this mystery code. I dont know what the code does. Can somone please explain with examples. (python 3.xx) from typing import Dict, TextIO, Tuple, List def exam(d1: Dict[str, List[int]], d2: Dict[int, int]) -> None: """ *Mystery code* """ for key in d1: value = d1[key] for i in range(len(value)): value[i] = d2[value[i]]   
Okay, can someone please tell me what I am doing wrong?? I will show the code...
Okay, can someone please tell me what I am doing wrong?? I will show the code I submitted for the assignment. However, according to my instructor I did it incorrectly but I am not understanding why. I will show the instructor's comment after providing my original code for the assignment. Thank you in advance. * * * * * HourlyTest Class * * * * * import java.util.Scanner; public class HourlyTest {    public static void main(String[] args)     {        ...
Below is my C++ program of a student record system. I have done the program through...
Below is my C++ program of a student record system. I have done the program through structures. Please do the same program using classes this time and dont use structures. Also, please make the menu function clean and beautiful if you can. So the output will look good at the end. Thanks. #include<iostream> #include<string> using namespace std; struct StudentRecord {    string name;    int roll_no;    string department;    StudentRecord *next; }; StudentRecord *head = NULL; StudentRecord *get_data() {...
please explain the solution and what it is wrong with my conception. FOLLOW the COMMENT PLEASE...
please explain the solution and what it is wrong with my conception. FOLLOW the COMMENT PLEASE Question: Let A and B are nonempty set bounded subset of R, and let A+B be the set of all sums a+b where a belngs to A and b belongs to B Prove Sup(A+B)=Sup(A)+Sup(B) Solution: Let ε>0, a is in A and b is in B, supA<=a+(ε/2), supB<=b+(ε/2) sup(A + B) ≥ a + b ≥ sup A − ε /2 + sup B...
HI can I please know whats wrong in this 2to1 mux code in VHDL code also...
HI can I please know whats wrong in this 2to1 mux code in VHDL code also please type it out so theres no confusion thank you -- Code your design here library IEEE; use IEEE.std_logic_1164.all; -- entity declaration for testbench entity test mux2 is end test; --architecture Body declaration for 2to1 mux -- component declaration of source entity 2to1 mux component test mux2 is port ( sel : in std_logic ; --select input, A : in std_logic ; --data input...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT