Game Development Reference
In-Depth Information
4 - Guess the Number
If the program doesn't seem to work after you've typed it, check to see if you have typed
the code exactly as it appears in this topic. You can also copy and paste your code to the
online "diff" tool at http://inventwithpython.com/diff. The diff tool will show you how your
code is different from the source code in this topic. In the file editor, press Ctrl-A to "Select
All" the text you've typed, then press Ctrl-C to copy the text to the clipboard. Then, paste
this text by clicking in the diff tool's text field on the website and click the "Compare"
button. The website will show you any differences between your code and the code in this
topic.
There is a diff tool for each program in this topic on the http://inventwithpython.com
website. A video tutorial of how to use the diff tool is available from this topic's website at
http://inventwithpython.com/videos/.
The import Statement
Let's look at each line of code in turn to see how this program works.
1. # This is a guess the number game.
This line is a comment. Comments were introduced in our Hello World program in
Chapter 3. Remember that Python will ignore everything after the # sign. This just reminds
us what this program does.
2. import random
This is an import statement . Statements are not functions (notice that neither import
nor random has parentheses after its name). Remember, statements are instructions that
perform some action but do not evaluate to a value. You have already seen statements:
assignment statements store a value into a variable (but the statement does not evaluate to
anything).
While Python includes many built-in functions, some functions exist in separate
programs called modules. Modules are Python programs that contain additional functions.
We use the functions of these modules by bringing them into our programs with the
import statement. In this case, we're importing the module random .
The import statement is made up of the import keyword followed by the module
name. Together, the keyword and module name make up the statement. Line 2 then is an
import statement that imports the module named random which contains several
functions related to random numbers. (We'll use one of these functions later to have the
computer come up with a random number for us to guess.)
4. guessesTaken = 0
Search WWH ::




Custom Search