Game Development Reference
In-Depth Information
>>> spam = 42
>>> print('Spam == ' + spam)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str
implicitly
>>>
You get this error because string concatenation can only combine two strings, and spam
is an integer. You would have to remember to put str(spam) in there instead. But with
string interpolation, you can have any data type. Try entering this into the shell:
>>> spam = 42
>>> print('Spam == %s' % (spam))
Spam == 42
>>>
As you can see, using string interpolation instead of string concatenation is much easier
because you don't have to worry about the data type of the variable. Also, string
interpolation can be done on any strings, not just strings used in print() function calls.
String interpolation is also known as string formatting .
How the Code Works: Lines 55 to 76
Now that the program has displayed the rules to Bagels to the player, the program will
randomly create a secret number and then enter a loop where it repeatedly asks for the
player's guesses until she has either correctly guessed the secret number, or has run out of
guesses. After that, we will ask the player if she wants to play again.
Creating the Secret Number
55. while True:
56. secretNum = getSecretNum(NUMDIGITS)
57. print('I have thought up a number. You have %s
guesses to get it.' % (MAXGUESS))
58.
59. numGuesses = 1
60. while numGuesses <= MAXGUESS:
We start with a while loop that has a condition of True , meaning it will loop forever
until we execute a break statement. Inside the infinite loop, we get a secret number from
Search WWH ::




Custom Search