Опубликован: 12.07.2013 | Доступ: свободный | Студентов: 975 / 36 | Длительность: 37:41:00
Лекция 4:

Guess the Number

< Лекция 3 || Лекция 4: 123 || Лекция 5 >
Аннотация: We are going to make a "Guess the Number" game. This is a good game for you to start with because it uses random numbers, loops, and input from the user in a fairly short program. As you write this game, you will learn how to convert values to different data types (and why you would need to do this).
Ключевые слова: comparison operator, guess, this, computer, random number, FROM, AND, ASK, GET, if, low, WIN, with, input, USER, short, AS, Write, convert, VALUES, Data, call, word, correct, look, LIKE, player, text, enter, save, clicking, Menu, explain, step, editor, attention, spacing, front, CAN, SEE, error, CHECK, ALL, download, book, URL, typing, Compare, online, email, COM, even, new, return, shell, individual, interactive, very, NOT, running, ITS, Button, Windows, mac, dock, bottom, screen, Top, Copy, paste, clipboard, field, video, tutorial, available, let, Line, comment, python, ignore, sign, NOR, random, parentheses, perform, evaluate, assignment statement, store, statement, while, built-in, separate, additional, CASE, MODULE, keyword, ONE, FAR, integer, SAW, reuse, function call, function, string, finish, precedence, period, function name, comma, secret, moment, go, back, TIME, roll, dice, Add, randomness, MOST, board, try, example, change, OLD, functional requirements, pass, argument, WHERE, First, extra, invisible, scope, greeting, useful, concept, concatenate, part, comparison, operating conditions, finally, lines of code, minimum, amount, indentation, block, total, diagram, black, count, previous, blank, decrease, idle, letter, Width, box, left margin, data type, case-sensitive, quote, Character, form, expression, operator, used, list, CONDITION, find, size, Height, false, difference, assignment operator, equal, assign, execution, NEXT, flow dependence, end, long, looping, true, setting, set, cause, course, crash, error condition, loop blocking, decrement, BIT, execute, jump, colon, break, RAN, reason, determine, appropriate, Left, DID, interpreter, programming, exact, keyboard, collection, flow of execution, Instruction, flow, control, skip, output, I/O, mouse, sound, Graphics, Last, play, programmer, Internet, Web, browser, trace, clear, simulation, actual, web page, right, section, hint, tracing

Topics Covered In This Chapter:

  • import statements
  • Modules
  • Arguments
  • while statements
  • Conditions
  • Blocks
  • Booleans
  • Comparison operators
  • The difference between = and ==.
  • if statements
  • The break keyword.
  • The str() and int() functions.
  • The random.randint() function.

The "Guess the Number" Game

We are going to make a "Guess the Number" game. In this game, the computer will think of a random number from 1 to 20, and ask you to guess the number. You only get six guesses, but the computer will tell you if your guess is too high or too low. If you guess the number within six tries, you win.

This is a good game for you to start with because it uses random numbers, loops, and input from the user in a fairly short program. As you write this game, you will learn how to convert values to different data types (and why you would need to do this).

Because this program is a game, we'll call the user the player, but the word "user" would be correct too.

Sample Run of "Guess the Number"

Here is what our game will look like to the player when the program is run. The text that the player types in is in bold.

Hello! What is your name?
Albert
Well, Albert, I am thinking of a number between 1
and 20.
Take a guess.
10
Your guess is too high. Take a guess.
2
Your guess is too low. Take a guess.
4
Good job, Albert! You guessed my number in 3 guesses!

Enter this code exactly as it appears here, and then save it by clicking on the File menu and then Save As. Give it a file name like guess.py then run it by pressing the F5 key. Don't worry if you don't understand the code now, I'll explain it step by step.

Guess the Number's Source Code

Here is the source code for our Guess the Number game. When you enter this code into the file editor, be sure to pay attention to the spacing at the front of some of the lines. Some lines have four or eight spaces in front of them. After you have typed in the code, save the file as guess.py. You can run the program from the file editor by pressing F5. If you see an error message, check that you have typed the program in exactly as written.

If you don't want to type all this code, you can download it from this book's website at the URL http://inventwithpython.com/chapter4.

Important Note! Be sure to run this program with Python 3, and not Python 2. The programs in this book use Python 3, and you'll get errors if you try to run them with Python 2. You can click on Help and then About IDLE to find out what version of Python you have.

guess.py

This code can be downloaded from http://inventwithpyt.hon.com/guess.py

If you get errors after typing this code in, compare it to the book's code with the online

diff tool at http://inventwithpython.com/diff or email the author at

al@inventwithpython.com

1.	# This is a guess the number game.
2.	import random 
3 .
4.	guessesTaken = 0 
5 .
6.	print('Hello! What is your name?')
7.	myName = input () 
8 .
9.	number = random.randint(1, 20)
10.	print('Well, ' + myName + ', I am thinking of a number
	between 1 and 2 0.')
11.
12.	while guessesTaken < 6:
13.	print('Take a guess.') # There are four spaces in front of print.
14.	guess = input ()
15.	guess = int(guess)
16.
17.    guessesTaken = guessesTaken + 1 
18 .
19.	if guess < number:
20.	print('Your guess is too low.') # There are eight spaces in front of print.
21.
22.	if guess > number:
23.	print('Your guess is too high.')
24.
25.	if guess == number:
26.	break
27.
28.	if guess == number:
29.	guessesTaken = str(guessesTaken)
30.	print('Good job, ' + myName + '! You guessed my number in ' + 
        guessesTaken + ' guesses!')
31.
32.	if guess != number:
33.	number = str(number)
34.	print('Nope. The number I was thinking of was ' + number)

Even though we are entering our source code into a new file editor window, we can return to the shell to enter individual instructions in order to see what they do. The interactive shell is very good for experimenting with different instructions when we are not running a program. You can return to the interactive shell by clicking on its window or on its taskbar button. In Windows or Mac OS X, the taskbar or dock is on the bottom of the screen. On Linux the taskbar may be located along the top of the screen.

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 book. 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 book. 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 book.

There is a diff tool for each program in this book on the http://inventwithpython.com website. A video tutorial of how to use the diff tool is available from this book'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 "Strings" . 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

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 "Strings" . 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 because each time the randint() function is called, it returns some random number, just like when you roll dice you will get a random number each time.

>>> import random
>>> random.randint(1, 20)
12
>>> random.randint(1, 20)
18
>>> random.randint(1, 20)
3
>>> random.randint(1, 20)
18
>>> random.randint(1, 20)
7
>>>

Whenever we want to add randomness to our games, we can use the randint() function. And we use randomness in most games. (Think of how many board games use dice.)

You can also try out different ranges of numbers by changing the arguments. For example, enter random.randint(1, 4) to only get integers between 1 and 4 (including both 1 and 4). Or try random.randint(1000, 2000) to get integers between 1000 and 2000. Here is an example of calling the random.randint() function and seeing what values it returns. The results you get when you call the random.randint() function will probably be different (it is random, after all).

>>> random.randint(1, 4)
3
>>> random.randint(1, 4)
4
>>> random.randint(1000, 2000)
1294
>>> random.randint(1000, 2000)
1585
>>>

We can change the game's code slightly to make the game behave differently. Try changing line 9 and 10 from this:

9. number = random.randint(1, 20) 10. print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
into these lines:
9. number = random.randint(1, 100) 10. print('Well, ' + name + ', I am thinking of a number between 1 and 100.')

And now the computer will think of an integer between 1 and 100. Changing line 9 will change the range of the random number, but remember to change line 10 so that the game also tells the player the new range instead of the old one.

< Лекция 3 || Лекция 4: 123 || Лекция 5 >