In: Computer Science
Exercise: What does the following program guess.py do? Write your answer in the file explanation.txt.
guess.py program
import random
number = random.randint(1, 25)
number_of_guesses = 0
while number_of_guesses < 5:
print('Guess a number between 1 and 25:')
guess = input()
guess = int(guess)
number_of_guesses += 1 if guess == number: break
Explanation:
The progam is a guessing game.
The user has to guess a number within five tries.
If the user, guesses within five tries then the program terminates.
If not, it will run until the user has tried five times.
Program imports random module to call the randint() function.
It generate a random integer between 1 and 25 by calling randint() function.
A variable is used as a counter to remember the number of guesses guessed by the user.
A while loop is used to iterate the guessing process.
Program:
#importing random module for randint() function
import random
#Generating a random number between 1 and 25 using randint()
function
number = random.randint(1, 25)
#variable to count number of guesses
number_of_guesses = 0
#Loop for five tries.
while number_of_guesses < 5:
print('Guess a number between 1 and 25:')
#input from user
guess = input()
#typecasting user input to int
guess = int(guess)
#incrementing the number of guesses
number_of_guesses += 1
#If the guess is correct exit the loop
if guess == number:
break
Sample Run 1:
Sample Run 2:
For Indentation: