Multi Stage Guessing Game in Python
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
#hashed lines are comment lines used to illustrate the program#import the built in method randint to generate an automatic secret numberfrom random import randint# intiate level or stage as 1 level = 1#loop for 3stageswhile level <= 3: #complexity range for each stage end_value = level * 10 #secret number generation secret_number = randint(1,end_value) #looping statment for 5 attempts at each stage for counter in range(0,5): #gets the guessing number as user input guess_number = int(input("Guess the secret number between 1 and {} ({} attempts left):".format(end_value,5-counter))) #check guessing number is correct or higher or lower if secret_number == guess_number: print("Your Guess is Correct, You Won the level {}".format(level)) level = level + 1 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)) breakelse: #else of while statement print("Congratz, You Won the Game!!!")
Program Explanation
Line 3: Imports the randint function from the package random
Line 5: initiate level or stage as 1
line 7: while loop for three stages
line 11 : using randint system generates a secret number
line 13 : looping statement to allow user 5 attempts
line 15 : getting guessing number from user as input
line 17 : check whether secret number generated by system and guessing number entered by user are same
line 18 : if same, display "your guess is correct"
line 19 : increase the stage or level by 1, so it moves to next stage
line 20 : breaks the current level (stage) and moves to next
line 21 : if not same, check whether guessing number entered by user is less than secret number generated by system
line 22 : if lower, display your guess is lower than the secret number
line 24 : if not, display your guess is higher than the secret number
line 25 : else statement of for statement (python only having this when compare to C, C++ and java)
line 26 : 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)
line 28 : else of while statement, executes if all three levels successfully completed.
Note (For is suitable for know number of iterations and while is suitable condition based iteration. example in inner loop for attempts we know 5 iterations needed. but in outer for loop it has to execute till level reaches 4, it may need any number of iteration based on user play)