Start Your Journey with Linux Command Line
![]() |
| Guess the secret number |
If you're taking PCAP - Programming Essentials In Python , you may have encountered this question in 3.2.1.3 LAB: Essentials of the while loop - Guess the secret number
A junior magician has picked a secret number. He has hidden it in a variable named secret_number. He wants everyone who run his program to play the Guess the secret number game, and guess what number he has picked for them. Those who don't guess the number will be stuck in an endless loop forever! Unfortunately, he does not know how to complete the code.
Your task is to help the magician complete the code in the editor in such a way so that the code:This lab turns a while loop into a small number-guessing game. A junior magician hides a value in a variable named secret_number set to 777 and asks every player to guess it. The program displays a welcome banner and prompts the user to enter an integer. The loop condition is while number != secret_number, which keeps looping as long as the guess differs from the secret. As long as the condition holds, the user sees the taunting message "Ha ha! You're stuck in my loop!" and is prompted to guess again.
The key to avoiding a genuinely endless loop is that the guess is re-read inside the loop body with another input() call. Because the input statement runs before the condition is tested again, each wrong guess gives the user a fresh chance, and the loop keeps evaluating whether the new value matches 777. As soon as the guess equals the secret number, the condition becomes False and the loop exits. The trailing else clause then prints the matched number plus the freeing message "Well done, muggle! You are free now."
If the input were read only once before the loop, the condition would never change and the user would truly be trapped forever, matching the magician's warning. Reading number inside the body guarantees that the loop can eventually terminate. This also shows that a while loop needs something within its body that can alter the value being tested; without such a change, the loop and its condition form an infinite cycle. By placing the prompt inside the loop, the program correctly converts each guess with int(input()) and compares it against the secret number on every pass.
number != secret_number, so any value other than 777 keeps it running.Because the loop must test a value that can change, so re-reading the guess lets the condition eventually become False and end the loop.
The condition would compare the same value forever, causing an endless loop with no way for the user to escape.
It runs once after the loop completes normally, which in this case happens only when the correct guess is made.
It wraps the input with int(), which converts the typed text into a number so it can be compared with the secret value.
Comments
Post a Comment
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.