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

Guess the Number

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

The Player Guesses

Lines 13 to 17 ask the player to guess what the secret number is and lets them enter their guess. We store this guess in a variable, and then convert that string value into an integer value.

13.	print('Take a guess.') # There are four spaces in front of print.
14.	guess = input ()

The program now asks us for a guess. We type in our guess and that number is stored in a variable named guess.

Converting Strings to Integers with the int() Function

15.    guess = int(guess)

In line 15, we call a new function called int(). The int() function takes one argument. The input() function returned a string of text that player typed. But in our program, we will want an integer, not a string. If the player enters 5 as their guess, the input() function will return the string value '5' and not the integer value 5. Remember that Python considers the string '5' and the integer 5 to be different values. So the int() function will take the string value we give it and return the integer value form of it.

Let's experiment with the int() function in the interactive shell. Try typing the following:

>>> int('42')
42
>>> int(42)
42
>>> int('hello')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module> int('forty-two')
ValueError: invalid literal for int() with base 10: 'hello' >>> int('forty-two')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module> int('forty-two')
ValueError: invalid literal for int() with base 10: 'forty-two' >>> int(' 42 ') 42
>>> 3 + int('2') 
5

We can see that the int('42') call will return the integer value 42, and that int(42) will do the same (though it is kind of pointless to convert an integer to an integer). However, even though you can pass a string to the int() function, you cannot just pass any string. For example, passing 'hello' to int() (like we do in the int('hello') call) will result in an error. The string we pass to int() must be made up of numbers.

The integer we pass to int() must also be numerical, rather than text, which is why 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 book, 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 loops around, guessesTaken will have the value of 1 and will be incremented to the value 2.

Is the Player's Guess Too Low?

Lines 19 and 20 check if the number that the player guessed is less than the secret random number that the computer came up with. If so, then we want to tell the player that their guess was too low by printing this message to the screen.

if Statements

19.	if guess < number:
20.	print('Your guess is too low.') # There are
eight spaces in front of print.

Line 19 begins an if statement with the keyword, if. Next to the if keyword is the condition. Line 20 starts a new block (you can tell because the indentation has increased from line 19 to line 20.) The block that follows the if keyword is called an if-block. An if statement is used if you only want a bit of code to execute if some condition is true. Line 19 has an if statement with the condition guess < number. If the condition evaluates to True, then the code in the if-block is executed. If the condition is False, then the code in the if-block is skipped.

Like the while statement, the if statement also has a keyword, followed by a condition, and then a block of code. See Figure 4.3 for a comparison of the two statements.

if and while statements.

Рис. 4.3. if and while statements.

The if statement works almost the same way as a while statement, too. But unlike the while-block, execution does not jump back to the if statement at the end of the if-block. It just continues on down to the next line. In other words, if blocks won't loop.

If the condition is True, then all the lines inside the if-block are executed. The only line inside this if-block on line 19 is a print() function call.

If the integer the player enters is less than the random integer the computer thought up, the program displays Your guess is too low. If the integer the player enters is equal to or larger than the random integer (in which case, the condition next to the if keyword would have been False), then this block would have been skipped over.

Is the Player's Guess Too High?

Lines 22 to 26 in our program check if the player's guess is either too big or exactly equal to the secret number.

22.	if guess > number:
23.	print('Your guess is too high.')

If the player's guess is larger than the random integer, we enter the if-block that follows the if statement. The print() line tells the player that their guess is too big.

Leaving Loops Early with the break Statement

25.	if guess == number:
26.	break

This if statement's condition checks to see if the guess is equal to the random integer. If it is, we enter line 26, the if-block that follows it.

The line inside the if-block is a break statement that tells the program to immediately jump out of the while-block to the first line after the end of the while-block. (The break statement does not bother re-checking the while loop's condition, it just breaks out immediately.)

The break statement is just the break keyword by itself, with no condition or colon (the : sign).

If the player's guess is not equal to the random integer, we do not break out of the while-block, we will reach the bottom of the while-block anyway. Once we reach the bottom of the while-block, the program will loop back to the top and recheck the condition (guessesTaken < 6). Remember after the guessesTaken = guessesTaken + 1 line of code executed, the new value of guessesTaken is 1. Because 1 is less than 6, we enter the loop again.

If the player keeps guessing too low or too high, the value of guessesTaken will change to 2, then 3, then 4, then 5, then 6. If the player guessed the number correctly, the condition in the if guess == number statement would be True, and we would have executed the break statement. Otherwise, we keep looping. But when guessesTaken has the number 6 stored, the while statement's condition is False, since 6 is not less than 6. Because the while statement's condition is False, we will not enter the loop and instead jump to the end of the while-block.

The remaining lines of code run when the player has finished guessing (either because the player guessed the correct number, or because the player ran out of guesses). The reason the player exited the previous loop will determine if they win or lose the game, and the program will display the appropriate message on the screen for either case.

Check if the Player Won

28. if guess == number:

Unlike the code in line 25, this line has no indentation, which means the while-block has ended and this is the first line outside the while-block. When we left the while block, we did so either because the while statement's condition was False (when the player runs out of guesses) or if we executed the break statement (when the player guesses the number correctly). With line 28, check again to see if the player guessed correctly. If so, we enter the if-block that follows.

29.	guessesTaken = str(guessesTaken)
30.	print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')

Lines 29 and 30 are inside the if-block. They only execute if the condition in the if statement on line 28 was True (that is, if the player correctly guessed the computer's number).

In line 29 (which is similar to the guess = int(guess) code on line 15), we call the new function str(), which returns the string form of an argument. We use this function because we want to change the integer value in guessesTaken into its string version because we can only use strings in calls to print().

Line 29 tells the player that they have won, and how many guesses it took them. Notice in this line that we change the guessesTaken value into a string because we can only add strings to other strings. If we were to try to add a string to an integer, the Python interpreter would display an error.

Check if the Player Lost

32. if guess != number:

In Line 32, we use the comparison operator != with the if statement's condition to mean "is not equal to." If the value of the player's guess is lower or higher than (and therefore, not equal to) the number chosen by the computer, then this condition evaluates to True, and we enter the block that follows this if statement on line 33.

Lines 33 and 34 are inside the if-block, and only execute if the condition is True.

33.	number = str(number)
34.	print('Nope. The number I was thinking of was ' + number)

In this block, we tell the player what the number is because they failed to guess correctly. But first we have to store the string version of number as the new value of number.

This line is also inside the if-block, and only executes if the condition was True. At this point, we have reached the end of the code, and the program terminates.

Congratulations! We've just programmed our first real game!

Summary: What Exactly is Programming?

If someone asked you, "What exactly is programming anyway?" what could you say to them? Programming is just the action of writing code for programs, that is, creating programs that can be executed by a computer.

"But what exactly is a program?" When you see someone using a computer program (for example, playing our Guess The Number game), all you see is some text appearing on the screen. The program decides what exact text to show on the screen (which is called the output), based on its instructions (that is, the program) and on the text that the player typed on the keyboard (which is called the input). The program has very specific instructions on what text to show the user. A program is just a collection of instructions.

"What kind of instructions?" There are only a few different kinds of instructions, really.

Expressions, which are made up of values connected by operators. Expressions are all evaluated down to a single value, like 2 + 2 evaluates to 4 or 'Hello' + ' ' + 'World' evaluates to 'Hello World'. Function calls are also part of expressions because they evaluate to a single value themselves, and this value can be connected by operators to other values. When expressions are next to the if and while keywords, we also call them conditions.

Assignment statements, which simply store values in variables so we can remember the values later in our program.

if, while and break are flow control statements because they decide which instructions are executed. The normal flow of execution for a program is to start at the top and execute each instruction going down one by one. But these flow control statements can cause the flow to skip instructions, loop over instructions, or break out of loops. Function calls also change the flow of execution by jumping to the start of a function.

The print() function, which displays text on the screen. Also, the input() function can get text from the user through the keyboard. This is called I/O (pronounced like the letters, "eye-oh"), because it deals with the input and output of the program.

And that's it, just those four things. Of course, there are many details about those four types of instructions. In this book you will learn about new data types and operators, new flow control statements besides if, while and break, and several new functions. There are also different types of I/O (input from the mouse, and outputting sound and graphics and pictures instead of just text.)

For the person using your programs, they really only care about that last type, I/O. The user types on the keyboard and then sees things on the screen or hears things from the speakers. But for the computer to figure out what sights to show and what sounds to play, it needs a program, and programs are just a bunch of instructions that you, the programmer, have written.

A Web Page for Program Tracing

If you have access to the Internet and a web browser, you can go to this book's website at http://inventwithpython.com/traces you will find a page that traces through each of the programs in this book. By following along with the trace line by line, it might become more clear what the Guess the Number program does. This website just shows a simulation of what happens when the program is run. No actual code is really being executed.

The tracing web page.

увеличить изображение
Рис. 4.4. The tracing web page.

The left side of the web page shows the source code, and the highlighted line is the line of code that is about to be executed. You execute this line and move to the next line by clicking the "Next" button. You can also go back a step by clicking the "Previous" button, or jump directly to a step by typing it in the white box and clicking the "Jump" button.

On the right side of the web page, there are three sections. The "Current variable values" section shows you each variable that has been assigned a value, along with the value itself. The "Notes" section will give you a hint about what is happening on the highlighted line. The "Program output" section shows the output from the program, and the input that is sent to the program. (This web page automatically enters text to the program when the program asks.)

So go to each of these web pages and click the "Next" and "Previous" buttons to trace through the program like we did above.

A video tutorial of how to use the online tracing tool is available from this book's website at http://inventwithpython.com/videos/.

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