Decode School

Multi Attempt Guessing Game with clues in Python

"Guessing Game with Five Attempts"
Create a simple guessing game in which the user must guess the secret number in five attempts. If the user correctly guessed the secret number, the system should display "your guess is correct" and end the game; otherwise, it should tell the user whether the guessed number is higher or lower than the secret number and proceed to the next attempt. If the user fails to guess correctly after five attempts, the game should end with the message "Game Over, You Lose the Game."
Hint : Basic looping (for or while) is enough for this.
Objective : To learn the usage of looping statement.

Program or Solution

					    
							
#hashed lines are comment lines used to illustrate the program
#import the built in method randint to generate an automatic secret number
from random import randint
secret_number = randint(1,10)
#looping statement for 5 attempts
for counter in range(0,5):
#gets the guessing number as user input
guess_number = int(input("Guess the secret number between 1 and 10 ({} attempts left):".format(5-counter)))
#check guessing number is correct or higher or lower
if secret_number == guess_number:
print("Your Guess is Correct, You Won the Game")
break
elif guess_number < secret_number:
print("Your Guess is lower than secret number")
else:
print("Your Guess is higher than secret number")
else: #else of for statement
print("Game Over, You Loose the Game, secret number is {}".format(secret_number))

Program Explanation

Line 3: Imports the randint function from the package random

Line 5: using randint system generates a secret number

Line 6 : looping statement to allow user 5 attempts

line 8 : getting guessing number from user as input

line 10 : check whether secret number generated by system and guessing number entered by user are same

line 11 : if same, display "your guess is correct"

line 12 : stops the game, if user guessed correctly

line 13 : if not same, check whether  guessing number entered by user is less than secret number generated by system

line 14 : if lower, display your guess is lower than the secret number

line 16 : if not, display your guess is higher than the secret number

line 17 : is else statement of for statement (python only having this when compare to C, C++ and java)

line 18 : executes after all the iterations of for (note : break statement doesn't allow to run else statement of for which means you guessed correctly this else will not work)