Question

In: Computer Science

Explain this python program as if you were going to present it to a class in...

Explain this python program as if you were going to present it to a class in a power point presentation. How would you explain it? I am having a hard time with this. I have my outputs and code displayed throughout 9 slides.

#Guess My Number Program
# Python Code is modified to discard duplicate guesses by the computer
import random
#function for getting the user input on what they want 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
guessed_numbers = [] #list of 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 than 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 than 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:
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):
#decreasing count by 1 because guess is already guessed.
countGuess = countGuess - 1;
#remove this line of code if you dont 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 the guesses.
print("\nThe computer guessed it! It took {} attempts".format(countGuess))
print("\nThe computer guessed the following numbers: "+str(guessed_numbers))
break
#if number guesses by computer is higher than user input
elif(compRand   
print("\nThe computer guessed {} which is too low".format(compRand))
#if number gueesed by computer is less than user input
else:
print("\nThe computer guessed {} which is too high".format(compRand))
break
  
def main():
print("Welcome to my Guess the number program!") #Printing welcome message
name = input("What's your name: ") #taking name of user as input
print("Hello ",name,) #greeting user
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 the 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
else: #For invalid choice print error message.
print("Invalid choice!!!")
#call the main function
main()

Solutions

Expert Solution

This is the guessing game .

It has tow parts

1) Computer selects the random number and you have to guess that number

2) You are select the secret number and computer is guess that number

now this program is divided into three module.

1) main

2) Menu

3) guessingGame

4) guessingGameComp

Main Module

first it will print the greeting message

then it will ask user's name

Now it will call the Menu function for taking user choice what user want to do

based on the user choice it will do the rest

if user choose the option 1 then it will call the guessingGame fucntion

if user choose the option 2 then it will call the guessingGameComp

and if user will choose option 3 then it will print the last greeting message and program will terminate

Module Menu

this is the function named menu

it will print the menu with three option

1. You guess the number

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

3. Exit"

and ask user to select the option .

if user select a number other then 1 to 3 then it will give an error

if user enter the any string or other then the int value then it will give an error for this i am using try catch block

and then user asked again to select the option

when user enter the valid option then this function will return the user choice to the main function.

guessingGame module

this function is called when user enter the 1 in menu module

in this function first numGuesses variable set to 0

and a random number between 1 to 10 is generated and stores int he variable called rand

then this function ask the user to guess the number between 1 to 10 and this number stored in variable called guess

then this user guessed number is add to the list named guessed_numbers

now it will check the guessed number is less then zero then asked again

otherwise there are three possibilites

1)

if it a positive number then it will compare with the rand number

then add 1 to the numGuesses

if user guessed number and rand number is both are equal then

then it will inform the user that he/she guessed the number in numGuesses attempt and print the list of guessed_numbers

2)

if guessed number is less then rand number then it will print too low and add 1 to the numGuesses

and again asked the user to guess another number

3)

if guessed number is greater then rand number then it will print too high and add 1 to the numGuesses

and again asked the user to guess another number

it also check user enter the number only if user enter the string or anything then it will give an error

this will continue untill user guess the true number

guessingGameComp module

in this countGuess var set to 0 it will track the number of guess comp required to guess the number

then initialize the guessed_numbers blank list it will hold all the non repeating guess of the computer

then it will ask user to enter a number between 1 to 10 ans stores in userNumber variable

if the number is between 1 and 10 then computer guess the number between 1 and 11 and stores it in compRand named variable

then this number is check to see if its preset in the guessed_numbers if it will preset then countGuess decremented by 1 and computer will guess another number

if this number is not present in the guessed_numbers list then there 3 posibilities again

1)

if compRand is equals to the userNumber then it will print the message the message comp guess in the countGuess number

and also print the guessed_numbers list

2)

if compRand is less then then userNumber then it will print the comp guess is low and it will increment the countGuess by 1

3)

if compRand is greater then then userNumber then it will print the comp guess is high and it will increment the countGuess by 1

this will continue untill computer will guess the number that is same as userguess

If you have any query regarding the answer please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.


Related Solutions

Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
In this python program , you are to build a trivia game. The game should present...
In this python program , you are to build a trivia game. The game should present each question – either in order or randomly – to the player, and display up to four possible answers. The player is to input what they believe to be the correct answer.   The game will tell the player if they got it right or wrong and will display their score. If they got it right, their score will go up. If they got it...
In this assignment, you are going to write a Python program to demonstrate the IPO (Input-Process-Output)...
In this assignment, you are going to write a Python program to demonstrate the IPO (Input-Process-Output) cycle that is the heart of many imperative programs used for processing large amount of data. Daisy is recently hired by a warehouse. One of her job is to keep track the items ordered by all the branches of the company. The company wants to automate the task using a computer program. Being a friend of Daisy, she knows you are a Computer Science...
If you were going to present the problems of environmental policy making and enforcement to others,...
If you were going to present the problems of environmental policy making and enforcement to others, what framework would you use?
In Python, create a program with 2 classes that do the following. HashCreate class, this class...
In Python, create a program with 2 classes that do the following. HashCreate class, this class will accept a directory and hash each file in the directory and store the results in a dictionary. The dictionary will contain the hash value and file name. HashVerify, the second class will accept the dictionary as input and save that in an instance attribute. This class must also contain a method for lookups that require a file path as input. The lookup method...
Given: You are given a Python Class template. In this class there is a class variable...
Given: You are given a Python Class template. In this class there is a class variable vector, is a list of N non-negative integers and are stored (in positions 0, 1, 2, ... (N-1)), where at least one integer is 0. Task: Write a recursive function "findAllPaths" to find all possible path through V starting at position 0, and ending at the location of 0, in accordance with the Rule below. If no such path exists, "paths" should be an...
In python please: You’re going to program a simulation of the following game. Like many probability...
In python please: You’re going to program a simulation of the following game. Like many probability games, this one involves an infinite supply of ping-pong balls. No, this game is "not quite beer pong." The balls are numbered 1 through N. There is also a group of N cups, labeled 1 through N, each of which can hold an unlimited number of ping-pong balls (a;ll numbered 1 through N). The game is played in rounds. A round is composed of...
In python 3.7: You’re going to program a simulation of the following game. Like many probability...
In python 3.7: You’re going to program a simulation of the following game. Like many probability games, this one involves an infinite supply of ping-pong balls. No, this game is "not quite beer pong." The balls are numbered 1 through N. There is also a group of N cups, labeled 1 through N, each of which can hold an unlimited number of ping-pong balls (all numbered 1 through N). The game is played in rounds. A round is composed of...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
For Python: In this assignment you are asked to write a Python program to determine the...
For Python: In this assignment you are asked to write a Python program to determine the Academic Standing of a studentbased on their CGPA. The program should do the following: Prompt the user to enter his name. Prompt the user to enter his major. Prompt the user to enter grades for 3 subjects (A, B, C, D, F). Calculate the CGPA of the student. To calculate CGPA use the formula: CGPA = (quality points * credit hours) / credit hours...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT