Game Development Reference
In-Depth Information
4 - Guess the Number
int('forty-two') also produces an error. That said, the int() function is slightly
forgiving- if our string has spaces on either side, it will still run without error. This is why
the int(' 42 ') call works.
The 3 + int('2') line shows an expression that adds an integer 3 to the return value
of int('2') (which evaluates to 2 as well). The expression evaluates to 3 + 2 , which
then evaluates to 5. So even though we cannot add an integer and a string ( 3 + '2'
would show us an error), we can add an integer to a string that has been converted to an
integer.
Remember, back in our program on line 15 the guess variable originally held the string
value of what the player typed. We will overwrite the string value stored in guess with the
integer value returned by the int() function. This is because we will later compare the
player's guess with the random number the computer came up with. We can only compare
two integer values to see if one is greater (that is, higher) or less (that is, lower) than the
other. We cannot compare a string value with an integer value to see if one is greater or less
than the other, even if that string value is numeric such as '5' .
In our Guess the Number game, if the player types in something that is not a number,
then the function call int() will result in an error and the program will crash. In the other
games in this topic, we will add some more code to check for error conditions like this and
give the player another chance to enter a correct response.
Notice that calling int(guess) does not change the value in the guess variable. The
code int(guess) is an expression that evaluates to the integer value form of the string
stored in the guess variable. We must assign this return value to guess in order to change
the value in guess to an integer with this full line: guess = int(guess)
Incrementing Variables
17. guessesTaken = guessesTaken + 1
Once the player has taken a guess, we want to increase the number of guesses that we
remember the player taking.
The first time that we enter the loop block, guessesTaken has the value of 0 . Python
will take this value and add 1 to it. 0 + 1 is 1 . Then Python will store the new value of 1
to guessesTaken .
Think of line 17 as meaning, "the guessesTaken variable should be one more than
what it already is".
When we add 1 to an integer value, programmers say they are incrementing the value
(because it is increasing by one). When we subtract one from a value, we are
decrementing the value (because it is decreasing by one). The next time the loop block 43
Search WWH ::




Custom Search