Question

Can you add code comments where required throughout this Python Program, Guess My Number Program, and...

Can you add code comments where required throughout this Python Program, Guess My Number Program, and describe this program as if you were presenting it to the class. What it does and everything step by step.


import random
def menu(): #function for getting the user input on what he wants to do
print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit")
while True:
#using try-except for the choice will handle the non-numbers
#if user enters letters, 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(): #user guesses the number generated randomly by the computer
min_number=1
max_number=10
#set number of guesses = 0
numGuesses=0
guessed_numbers = [] # list of guessed numbers
rand=random.randint(min_number, max_number)
#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:"))
guessed_numbers.append(guess)
#check if the guess is less than 0, then continue 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 {} attempts".format(numGuesses))
# print the guesses numbers list
print('You picked the following numbers: '+str(guessed_numbers))
#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!")
  
# In guessingGameComp function, computer will guess the number entered by the user. I have modified the code so that wherever computer generates same random number again, it will not be taken into account.
# For e.g., if initially computer guessed the number to be 3, and again it tries to guess the number 3.So, this limitation is removed
def guessingGameComp():
countGuess=0 #initially, number of guess attempts 0.
guessed_numbers = [] # list of guessed numbers
  
#taking input number from user
userNumber=int(input("\nPlease enter a number between 1 and 10 for the computer to guess:"))
  
#execute below loop only when number entered by user is between 0 and 11.
while userNumber > 0 and userNumber < 11:
while True:
countGuess+=1 #counting the attempts by computer
compRand = random.randint(1,10) #random number guessed by computer
#if compRand is already guesses, do not count this attempt
if(compRand in guessed_numbers):
countGuess = countGuess - 1;
print("\n Already guessed number: ", compRand) #remove this line of code if you don't want to show already guessed numbers.
continue
guessed_numbers.append(compRand) #add valid guessed number to guessed_numbers list
if(userNumber==compRand): #if number guessed by computer is correct, break out of loop.
print("\nThe computer guessed it! It took {} attempts".format(countGuess))
print("\nThe computer guessed the following numbers: "+str(guessed_numbers))
break
elif(compRand print("\nThe computer guessed {} which is too low".format(compRand))
else: #if number gueesed by computer is higher than user input
print("\nThe computer guessed {} which is too high".format(compRand))
break
  
def main():
print("Welcome to my Guess the number program!")
name = input("What's your name: ") #taking name of user as input
print("Hi ",name,) #greeting user
while True:
userChoice=menu()
if userChoice==1:
guessingGame()
elif userChoice==2:
guessingGameComp()
elif userChoice==3:
print("\nThanks", name, "for playing the guess the number game!") #greeting user after the game ended.
break
else:
print("Invalid choice!!!")
#call the main function
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Explained step by step and in comments as well.

Steps:

1) Code execution will start from:

This will call main function.

2) This is main method :

3) Now this function will take user input using :

4) Now if user chooses 1 then this is called :

5) If 2 is chosen then this function is called:

6) This two choices will continue until user presses 3 to exit.

Full Code:

import random

#function for getting the user input on what he wants to do
def menu():
#Print the options
print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit")
#Loop until correct choice is entered
while True:
#using try-except for the choice will handle the non-numbers
#if user enters letters, then except will show the message, Numbers only!
try:
#Taking input and converting to integer
c=int(input("Enter your choice: "))
#if input is correct return number
if(c>=1 and c<=3):
return c
#if input is not correct print message and ask again
else:
print("Enter number between 1 and 3 inclusive.")
#For non numeric input throw exception
except:
#print exception
print("Numbers Only!")

#This function is the main game for the player.
def guessingGame(): #user guesses the number generated randomly by the computer
#defining minimum and maximum value
min_number=1
max_number=10
#set number of guesses = 0
numGuesses=0
# list of guessed numbers
guessed_numbers = []
#Generating a random number between min and max which user has to guess
rand=random.randint(min_number, max_number)
#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:
#Asking for input from the player
guess=eval(input("Please try to guess my number between 1 and 10:"))
#Adding guess to list of guesses
guessed_numbers.append(guess)
#check if the guess is less than 0, then continue to beginning of the loop
if(guess<0):
continue;
#If guess is correct print results
elif (guess==rand):
#increment the guess count by 1
numGuesses=numGuesses+1
#Print results
print("You guessed it! It took you {} attempts".format(numGuesses))
# print the guesses numbers list
print('You picked the following numbers: '+str(guessed_numbers))
#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
#If guess is lower then actual then increasing guess count and print low message
elif(guess < rand):
#increment the guess count by 1
numGuesses = numGuesses +1
print("Too low")
#If guess is higher then actual then increasing guess count and print low message
else:
#increment the guess count by 1
numGuesses = numGuesses + 1
print("Too high")
except:
#print exception
print("Numbers only!")
  
# In guessingGameComp function, computer will guess the number entered by the user. I have modified the code so that wherever computer generates same random number again, it will not be taken into account.
# For e.g., if initially computer guessed the number to be 3, and again it tries to guess the number 3.So, this limitation is removed
def guessingGameComp():
countGuess=0 #initially, number of guess attempts 0.
guessed_numbers = [] # list of guessed numbers
  
#taking input number from user
userNumber=int(input("\nPlease enter a number between 1 and 10 for the computer to guess:"))
  
#execute below loop only when number entered by user is between 0 and 11.
while userNumber > 0 and userNumber < 11:
while True:
#counting the attempts by computer
countGuess+=1
#random number guessed by computer
compRand = random.randint(1,10)
#if compRand is already guesses, do not count this attempt
if(compRand in guessed_numbers):
#decreasing count by 1 because guess is already guessed
countGuess = countGuess - 1;
#remove this line of code if you don't want to show already guessed numbers.
print("\n Already guessed number: ", compRand)
continue
#add valid guessed number to guessed_numbers list
guessed_numbers.append(compRand)
#if number guessed by computer is correct, break out of loop.
if(userNumber==compRand):
#If guess is correct print list of guesses and count of guesses
print("\nThe computer guessed it! It took {} attempts".format(countGuess))
print("\nThe computer guessed the following numbers: "+str(guessed_numbers))
break
#if number gueesed by computer is higher than user input
elif(compRand>userNumber):
print("\nThe computer guessed {} which is too high".format(compRand))
#if number gueesed by computer is lower than user input
else:
print("\nThe computer guessed {} which is too high".format(compRand))
break

#Program Starts from here
def main():
#printing welcome message
print("Welcome to my Guess the number program!")
#taking name of user as input
name = input("What's your name: ")
#greeting user
print("Hi ",name,)
while True:
#Show menu and take input from user
userChoice=menu()
#If user choice is 1 this means player will play game
if userChoice==1:
guessingGame()
#If user choice is 2 this means computer will play game
elif userChoice==2:
guessingGameComp()
#If choice is 3 then user will exit the game
elif userChoice==3:
print("\nThanks", name, "for playing the guess the number game!") #greeting user after the game ended.
break
#For invalid choice print error message
else:
print("Invalid choice!!!")
  
#call the main function
main()

Code Screenshot:

Add a comment
Know the answer?
Add Answer to:
Can you add code comments where required throughout this Python Program, Guess My Number Program, and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? 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: #using try-except for the choice will handle the non-numbers #if user enters letters, 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!")...

  • python code for guessing game users enter the number the computer will guess 8:38 PM 100...

    python code for guessing game users enter the number the computer will guess 8:38 PM 100 nstructure.com 1. Number guessing game : (5 points) 1) Requirements: Your program will ask the user to enter a number between 1 and 1000. Then it will try to guess the correct number with the guaranteed minimal average number of guesses. Which search algorithm should you use? 2) Expected Output: Enter a number between 1 and 1000? 784 Computer guesses: 500 Type 'l' if...

  • Write a program to play "guess my number". The program should generate a random number between...

    Write a program to play "guess my number". The program should generate a random number between 0 and 100 and then prompt the user to guess the number. If the user guesses incorrectly the program gives the user a hint using the words 'higher' or 'lower' (as shown in the sample output). It prints a message 'Yes - it is' if the guessed number is same as the random number generated. ANSWER IN C LANGUAGE. ====================== Sample Input / Output:...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • This is python code I am having trouble with the both winning messages printing if the...

    This is python code I am having trouble with the both winning messages printing if the user guesses in 1 try. 1 message or the other should print depending on the number of guesses not both. Thank you for your help! import random answer = 5 tries = 0 user_guess = "" while True: user_guess = int(input("enter a number between 1 and 10: ")) tries = tries + 1    if user_guess == answer: print ("You win! \nIt took you",...

  • Can someone upload a picture of the code in matlab Write a "Guess My Number Game"...

    Can someone upload a picture of the code in matlab Write a "Guess My Number Game" program. The program generates a random integer in a specified range, and the user (the player) has to guess the number. The program allows the use to play as many times as he/she would like; at the conclusion of each game, the program asks whether the player wants to play again The basic algorithm is: 1. The program starts by printing instructions on the...

  • Part 1: Python code; rewrite this code in C#, run the program and submit - include...

    Part 1: Python code; rewrite this code in C#, run the program and submit - include comments number= 4 guesscount=0 guess=int(input("Guess a number between 1 and 10: ")) while guess!=number: guesscount=guesscount+1 if guess<number: print("Your guess is too low") elif guess>number: print("Your guess is too high") else: print("You got it!!") guess=int(input("Guess again: ")) print("You figured it out in ",guesscount," guesses") Part 2: C++ code; rewrite the following code in C#. Run the program and submit. - include comments #include <iostream> using...

  • on python i need to code a guessing game. After the player has guessed the random...

    on python i need to code a guessing game. After the player has guessed the random number correctly, prompt the user to enter their name. Record the names in a list along with how many tries it took them to reach the unknown number. Record the score for each name in another list. When the game is quit, show who won with the least amount of tries. this is what i have so far: #Guess The Number HW assignment import...

  • In python how could I update my code to tell me the number of guesses it...

    In python how could I update my code to tell me the number of guesses it took my to get the correct number here is my working code so far import random number = random.randint(1,100) total_guess = 0 while total_guess<=100: guess = int(input("what is your guess?")) print (guess) total_guess = total_guess + 1 if guess<number: print("Too low") if guess>number: print("Too high") if guess==number: print("Correct!") break

  • In c# create a program that generates a random number from 1 to 1000. Then, ask...

    In c# create a program that generates a random number from 1 to 1000. Then, ask the user to guess the random number. If the user's guess is too high, then the program should print "Too High, Try again". If the user's guess is too low, then the program should print "Too low, Try again". Use a loop to allow the user to keep entering guesses until they guess the random number correctly. Once they figure it, congratulate the user....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT