Game Development Reference
In-Depth Information
4 - Guess the Number
If the integer the player enters is less than the random integer the computer thought up,
the program displays Your guess is too low . If the integer the player enters is
equal to or larger than the random integer (in which case, the condition next to the if
keyword would have been False ), then this block would have been skipped over.
Is the Player's Guess Too High?
Lines 22 to 26 in our program check if the player's guess is either too big or exactly
equal to the secret number.
22. if guess > number:
23. print('Your guess is too high.')
If the player's guess is larger than the random integer, we enter the if-block that follows
the if statement. The print() line tells the player that their guess is too big.
Leaving Loops Early with the break Statement
25. if guess == number:
26. break
This if statement's condition checks to see if the guess is equal to the random integer. If
it is, we enter line 26, the if-block that follows it.
The line inside the if-block is a break statement that tells the program to immediately
jump out of the while-block to the first line after the end of the while-block. (The break
statement does not bother re-checking the while loop's condition, it just breaks out
immediately.)
The break statement is just the break keyword by itself, with no condition or colon
(the : sign).
If the player's guess is not equal to the random integer, we do not break out of the while-
block, we will reach the bottom of the while-block anyway. Once we reach the bottom of
the while-block, the program will loop back to the top and recheck the condition
( guessesTaken < 6 ). Remember after the guessesTaken = guessesTaken +
1 line of code executed, the new value of guessesTaken is 1 . Because 1 is less than 6 ,
we enter the loop again.
If the player keeps guessing too low or too high, the value of guessesTaken will
change to 2 , then 3 , then 4 , then 5 , then 6 . If the player guessed the number correctly, the
condition in the if guess == number statement would be True , and we would have
Search WWH ::




Custom Search