In: Computer Science
Random Number Guessing Game
(python)
*use comments
Write a program guess.py that generates a random number in the range of 1 through 20, and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." If the user guesses the number, the application should congratulate the user and generate a new random number so the game can start over. If the user enters 0, they can exit out of the game.
Do not use break or exit() or continue etc.
Use the following code to have the computer pick a random number between 1 and 20 (inclusive):
import random # Place this line at the top of your program
#Place the line below at the appropriate place in your program:
number = random.randint(1, 20) # Generates random number from 1 to 20
Write a value returning function playGuessingGame(number) that takes in the number that the computer randomly generated as a parameter. It should ask for the user's input by asking 'Enter a number between 1 and 20, or 0 to quit:' , see if the guess is correct, and return the user's guess. If the user enters the correct number the function should congratulate them with 'Congratulations! You guessed the right number!'. The function should return the user's guess (even if they enter zero). (You do not need to worry about invalid values.)
Write a main function that calls the playGuessingGame method and keeps looping through until the user enters zero. Once they exit out of the game print 'Thanks for playing!'
#Feel free to ask queries!/ This program is successfully compiled and tested in Python 3.6 version
import random
def playGuessingGame(number):
guess=int(input("Enter a number between 1 and 20,0 to quit"))
if guess < number and guess != 0:
print("Too low,Try again")
elif guess > number:
print("Too high,Try again")
elif guess == number:
print("Congatulations!")
num=random.randint(1,20)# If the guess is correct then new random number is generated to start another game/
return guess
#The main function is used to keep track of loop until the user enter "0" and if not then compiler calls the playGuessingGame function
def main():
var=1
num=random.randint(1,20)
while var:
var=playGuessingGame(num) #The return value of playGuessingGame function is stored in var
print("Thanks for playing!")
if __name__ == "__main__":
main() #This is used to call the main() function