player types hello, the except block catches the error and
prompts the player to enter a valid number.
python try: guess = intinputGuess a number between 1 and 100:
except ValueError: printInvalid input. Please enter a number.
continue # Go back to the beginning of the loop
Check the Guess : Now we compare the players guess to the
secretnumber.
If guess is correct, we break out of the while loop.
If guess is too high, print Too high.
If guess is too low, print Too low.
python if guess == secretnumber: break elif guess secretnumber:
printToo high else: printToo low
: Regardless of whether the guess was too
c
Increment Attempts
high or too low, we increment the attempts counter by one.
do
This keeps track of how many tries the player has made. The
increment operator is attempts += 1 or simply attempts =
gs
attempts + 1.
python attempts += 1
3. The Final Reveal
After the while loop finishes meaning the player guessed
correctly, we print a message congratulating them and revealing
the number of attempts it took.
python printfYou guessed it The number was secretnumber
printfIt took you attempts attempts.
Putting it all together, the complete code looks something like
this:
python import random
secretnumber = random.randint1, 100 guess = 0 attempts = 0
while True: try: guess = intinputGuess a number between 1 and
100: except ValueError: printInvalid input. Please enter a number.
continue
if guess == secretnumber:
break
elif guess secretnumber:
printToo high
else:
printToo low
attempts += 1
printfYou guessed it The number was secretnumber printfIt took
you attempts attempts.
This challenge is designed to help solidify your understanding of
fundamental programming concepts like random number
generation, variables, while loops, conditional statements
c
if/elif/else, input/output, and error handling. Good luck, and
do
happy coding
gs