This program is a guessing game implemented in Python. The program starts by importing the random module, which is used to generate random numbers.
The program starts by importing the
random
module, which is used to generate random numbers.
The play_guessing_game()
function is defined to encapsulate the guessing game logic.
Inside the function, a random number between 1 and 100 is generated using random.randint(1, 100)
and stored in the number
variable. The attempts
variable is initialized to keep track of the number of attempts made by the player.
The player is greeted with a welcome message and informed that they need to guess a number between 1 and 100.
A while
loop is started to repeatedly prompt the player for their guess.
Within the loop, the player's input is obtained using input()
and converted to an integer using int()
. The number of attempts is incremented by 1.
The player's guess is then compared with the randomly generated number. If the guess is lower than the number, a message is displayed to try a higher number. If the guess is higher, a message is displayed to try a lower number. If the guess matches the number, a congratulatory message is printed, displaying the number of attempts made, and the loop is exited using break
.
If the player reaches the maximum number of attempts (in this case, 5), a message is printed to inform them. The correct number is revealed, and the loop is exited.
After the loop, a thank-you message is displayed to the player.
By calling play_guessing_game()
, the program initiates the guessing game.
This program generates a random number and allows the player to guess it within a certain number of attempts. It provides feedback based on the player's guesses and informs them if they have won or reached the maximum attempts.
The program can be customized by modifying the range of the random number, the maximum number of attempts, or by adding additional features or validation checks.
Submitted by Padavala komala sri (Komala)
Download packets of source code on Coders Packet
Comments