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

Guess the Number

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

Calling Functions that are Inside Modules

By the way, be sure to enter random.randint(1, 20) and not just randint(1, 20), or the computer will not know to look in the random module for the randint() function and you'll get an error like this:

>>> randint(1, 20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> 
  NameError: name 'randint' is not defined 
>>>

Remember, your program needs to run import random before it can call the random.randint() function. This is why import statements usually go at the beginning of the program.

Passing Arguments to Functions

The integer values between the parentheses in the random.randint(1, 20) function call are called arguments. Arguments are the values that are passed to a function when the function is called. Arguments tell the function how to behave. Just like the player's input changes how our program behaves, arguments are inputs for functions.

Some functions require that you pass them values when you call them. For example, look at these function calls:

input()
print('Hello') random.randint(1, 20)

The input() function has no arguments but the print() function call has one and the randint() function call has two. When we have more than one argument, we separate each with commas, as you can see in this example. Programmers say that the arguments are delimited (that is, separated) by commas. This is how the computer knows where one value ends and another begins.

If you pass too many or too few arguments in a function call, Python will display an error message, as you can see below. In this example, we first called randint() with only one argument (too few), and then we called randint() with three arguments (too many).

>>> random.randint(1)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module> 
random.randint(1)
TypeError: randint() takes exactly 3 positional arguments (2 given) 
>>> random.randint(1, 2, 3) 
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module> 
random.randint(1, 2, 3)
TypeError: randint() takes exactly 3 positional arguments (4 given) 
>>>

Notice that the error message says we passed 2 and 4 arguments instead of 1 and 3. This is because Python always passes an extra, invisible argument. This argument is beyond the scope of this book, and you don't have to worry about it.

Welcoming the Player

Lines 10 and 12 greets the player and tells them about the game, and then starts letting the player guess the secret number. Line 10 is fairly simple, but line 12 introduces a useful concept called a loop.

10. print('Well, ' + myName + ', I am thinking of a number between 1 and 2 0.')

In Line 10 the print() function welcomes the player by name, and tells them that the computer is thinking of a random number.

But wait - didn't I say that the print() function takes only one string? It may look like there's more than one string there. But look at the line carefully. The plus signs concatenate the three strings to evaluate down to one string, and that is the one string the print() function prints. It might look like the commas are separating the strings, but if you look closely you see that the commas are inside the quotes, and part of the strings themselves.

Loops

Line 12 has something called a while statement, which indicates the beginning of a while loop. Loops are parts of code that are executed over and over again. But before we can learn about while loops, we need to learn a few other concepts first. Those concepts are blocks, booleans, comparison operators, conditions, and finally, the while statement.

Blocks

A block is one or more lines of code grouped together with the same minimum amount of indentation. You can tell where a block begins and ends by looking at the line's indentation (that is, the number of spaces in front of the line).

A block begins when a line is indented by four spaces. Any following line that is also indented by four spaces is part of the block. A block within a block begins when a line is indented with another four spaces (for a total of eight spaces in front of the line). The block ends when there is a line of code with the same indentation before the block started.

Below is a diagram of the code with the blocks outlined and numbered. The spaces have black squares filled in to make them easier to count.

Blocks and their indentation. The black dots represent spaces.

Рис. 4.1. Blocks and their indentation. The black dots represent spaces.

For example, look at the code above. The spaces have been replaced with dark squares to make them easier to count. Line 12 has an indentation of zero spaces and is not inside any block. Line 13 has an indentation of four spaces. Since this indentation is larger than the previous line's indentation, we can tell that a new block has started. Lines 14, 15, 17 and 19 also have four spaces for indentation. Both of these lines have the same amount of indentation as the previous line, so we know they are in the same block. (We do not count blank lines when we look for indentation.)

Line 20 has an indentation of eight spaces. Eight spaces is more than four spaces, so we know a new block has started. This is a block that is inside of another block.

Line 22 only has four spaces. The line before line 22 had a larger number of spaces. Because the indentation has decreased, we know that block has ended. Line 22 is in the same block as the other lines with four spaces.

Line 23 increases the indentation to eight spaces, so again a new block has started.

To recap, line 12 is not in any block. Lines 13 to 23 all in one block (marked with the circled 1). Line 20 is in a block in a block (marked with a circled 2). And line 23 is the only line in another block in a block (marked with a circled 3).

When you type code into IDLE, each letter is the same width. You can count the number of letters above or below the line to see how many spaces you have put in front of that line of code.

In this figure, the lines of code inside box 1 are all in the same block, and blocks 2 and 3 are inside block 1. Block 1 is indented with at least four spaces from the left margin, and blocks 2 and 3 are indented eight spaces from the left margin. A block can contain just one line. Notice that blocks 2 and 3 are only one line each.

The Boolean Data Type

The Boolean data type has only two values: True or False. These values are case-sensitive and they are not string values; in other words, you do not put a ' quote character around them. We will use Boolean values with comparison operators to form conditions. (See below.)

Comparison Operators

In line 12 of our program, the line of code containing the while statement:

12. while guessesTaken < 6:

The expression that follows the while keyword (guessesTaken < 6) contains two values (the value in the variable guessesTaken, and the integer value 6) connected by an operator (the < sign, the "less than" sign). The < sign is called a comparison operator.

The comparison operator is used to compare two values and evaluate to a True or False Boolean value. A list of all the comparison operators is in Table 4.1.

Таблица 4.1. Comparison operators.
Operator Sign Operator Name
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Conditions

A condition is an expression that combines two values with a comparison operator (such as < or >) and evaluates to a Boolean value. A condition is just another name for an expression that evaluates to True or False. You'll find a list of other comparison operators in Table 4.1.

Conditions always evaluate to a Boolean value-either True or False. For example, the condition in our code, guessesTaken < 6 asks "is the value stored in guessesTaken less than the number 6?" If so, then the condition evaluates to True. If not, the condition evaluates to False.

In the case of our Guess the Number program, in line 4 we stored the value 0 in guessesTaken. Because 0 is less than 6, this condition evaluates to the Boolean value of True. Remember, a condition is just a name for an expression that uses comparison operators such as < or !=.

Experiment with Booleans, Comparison Operators, and Conditions

Enter the following expressions in the interactive shell to see their Boolean results:

>>> 0 < 6
True
>>> 6 < 0
False
>>> 50 < 10
False
>>> 10 < 11
True
>>> 10 < 10
 
False

The condition 0 < 6 returns the Boolean value True because the number 0 is less than the number 6. But because 6 is not less than 0, the condition 6 < 0 evaluates to False. 50 is not less than 10, so 50 < 10 is False. 10 is less than 11, so 10 < 11 is True.

But what about 10 < 10? Why does it evaluate to False? It is False because the number 10 is not smaller than the number 10. They are exactly the same size. If a girl named Alice was the same height as a boy named Bob, you wouldn't say that Alice is taller than Bob or that Alice is shorter than Bob. Both of those statements would be false.

Try entering some conditions into the shell to see how these comparison operators work:

>>> 10 == 10
True
>>> 10 == 11
False
>>> 11 == 10
False
>>> 10 != 10
False
>>> 10 != 11
True
>>> 'Hello' == 'Hello'
True
>>> 'Hello' == 'Good bye'
False
>>> 'Hello' == 'HELLO'
False
>>> 'Good bye' != 'Hello'
True

Notice the difference between the assignment operator (=) and the "equal to" comparison operator (==). The equal (=) sign is used to assign a value to a variable, and the equal to (==) sign is used in expressions to see whether two values are equal. It's easy to accidentally use one when you meant to use the other, so be careful of what you type in.

Two values that are different data types will always be not equal to each other. For example, try entering the following into the interactive shell:

>>> 42 == 'Hello'
False
>>> 42 != 'Hello'
True

Looping with While Statements

The while statement marks the beginning of a loop. Sometimes in our programs, we want the program to do something over and over again. When the execution reaches a while statement, it evaluates the condition next to the while keyword. If the condition evaluates to True, the execution moves inside the while-block. (In our program, the while-block begins on line 13.) If the condition evaluates to False, the execution moves all the way past the while-block. (In our program, the first line after the while-block is line 28.)

12. while guessesTaken < 6:
The while loop's condition.

Рис. 4.2. The while loop's condition.

Figure 4.2 shows how the execution flows depending on the condition. If the condition evaluates to True (which it does the first time, because the value of guessesTaken is 0), execution will enter the while-block at line 13 and keep going down. Once the program reaches the end of the while-block, instead of going down to the next line, it jumps back up to the while statement's line (line 12). It then re-evaluates the condition, and if it is True we enter the while-block again.

This is how the loop works. As long as the condition is True, the program keeps executing the code inside the while-block repeatedly until we reach the end of the while-block and the condition is False. And, until guessesTaken is equal to or greater than 6, we will keep looping.

Think of the while statement as saying, "while this condition is true, keep looping through the code in this block".

You can make this game harder or easier by changing the number of guesses the player gets. All you have to do is change this line:

12. while guessesTaken < 6:

into this line:

12. while guessesTaken < 4:

...and now the player only gets four guesses instead of six guesses. By setting the condition to guessesTaken < 4, we ensure that the code inside the loop only runs four times instead of six. This makes the game much more difficult. To make the game easier, set the condition to guessesTaken < 8 or guessesTaken < 10, which will cause the loop to run a few more times than before and accept more guesses from the player.

Of course, if we removed line 17 altogether then the guessesTaken would never increase and the condition would always be True. This would give the player an unlimited number of guesses.

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