Game Development Reference
In-Depth Information
This line creates a new variable named guessesTaken . We'll store the number of
guesses the player makes in this variable. Since the player hasn't made any guesses so far,
we store the integer 0 here.
6. print('Hello! What is your name?')
7. myName = input()
Lines 6 and 7 are the same as the lines in the Hello World program that we saw in
Chapter 3. Programmers often reuse code from their other programs when they need the
program to do something that they've already coded before.
Line 6 is a function call to the print() function. Remember that a function is like a
mini-program that our program runs, and when our program calls a function it runs this
mini-program. The code inside the print() function displays the string you passed it
inside the parentheses on the screen.
When these two lines finish executing, the string that is the player's name will be stored
in the myName variable. (Remember, the string might not really be the player's name. It's
just whatever string the player typed in. Computers are dumb and just follow their
programs no matter what.)
The random.randint() Function
9. number = random.randint(1, 20)
In Line 9 we call a new function named randint() , and then store the return value in
a variable named number . Remember that function calls are expressions because they
evaluate to a value. We call this value the function call's return value.
Because the randint() function is provided by the random module, we precede it
with random. (don't forget the period!) to tell our program that the function randint()
is in the random module.
The randint() function will return a random integer between (and including) the two
integers we give it. Here, we give it the integers 1 and 20 between the parentheses that
follow the function name (separated by a comma). The random integer that randint()
returns is stored in a variable named number -this is the secret number the player is trying
to guess.
Just for a moment, go back to the interactive shell and enter import random to
import the random module. Then enter random.randint(1, 20) to see what the
function call evaluates to. It should return an integer between 1 and 20 . Now enter the
same code again and the function call will probably return a different integer. This is
Search WWH ::




Custom Search