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

Dragon Realm

< Лекция 5 || Лекция 6: 123 || Лекция 7 >

Experimenting with the not Operator

The third boolean operator is not. The not operator is different from every other operator we've seen before, because it only works on one value, not two. There is only value on the right side of the not keyword, and none on the left. The not operator will evaluate to True as False and will evaluate False as True.

Try typing the following into the interactive shell:

>>> not True
>>> not False
>>> True not
SyntaxError: invalid syntax (<pyshell#0>, line 1)

Notice that if we put the boolean value on the left side of the not operator results in a syntax error.

We can use both the and and not operators in a single expression. Try typing True and not False into the shell:

>>> True and not False True

Normally the expression True and False would evaluate to False. But the True and not False expression evaluates to True. This is because not False evaluates to True, which turns the expression into True and True, which evaluates to True.

Truth Tables

If you ever forget how the boolean operators work, you can look at these charts, which are called truth tables:

Таблица 6.1. The and operator's truth table.
A and B is Entire statement
True and True is True
True and False is False
False and True is False
False and False is False
Таблица 6.2. The or operator's truth table.
A or B is Entire statement
True or True is True
True or False is True
False or True is True
False or False is False
Таблица 6.3. The not operator's truth table.
not A is Entire statement
not True is False
not False is True

Getting the Player's Input

14 . print('Which cave will cave = input ()
15 . you go into? (1 or 2)')

Here, the player is asked to enter which cave they chose to enter by typing in 1 or 2 and hitting Enter. Whatever string the player typed will be stored in cave. After this code is executed, we jump back to the top of the while statement and recheck the condition. Remember that the line was:

13 . while cave != '1' and cave != '2':

If this condition evaluates to True, we will enter the while-block again and ask the player for a cave number to enter. But if the player typed in 1 or 2, then the cave value will either be '1' or '2'. This causes the condition to evaluate to False, and the program execution will continue on past the while loop.

The reason we have a loop here is because the player may have typed in 3 or 4 or HELLO. Our program doesn't make sense of this, so if the player did not enter 1 or 2, then the program loops back and asks the player again. In fact, the computer will patiently ask the player for the cave number over and over again until the player types in 1 or 2. When the player does that, the while-block's condition will be False, and we will jump down past the while-block and continue with the program.

Return Values

17.     return cave

This is the return keyword, which only appears inside def-blocks. Remember how the input() function returns the string value that the player typed in? Or how the randint () function will return a random integer value? Our function will also return a value. It returns the string that is stored in cave.

This means that if we had a line of code like spam = chooseCave(), the code inside chooseCave() would be executed and the function call will evaluate to chooseCave()'s return value. The return value will either be the string '1' or the string '2'. (Our while loop guarantees that chooseCave() will only return either '1' or '2'.)

The return keyword is only found inside def-blocks. Once the return statement is executed, we immediately jump out of the def-block. (This is like how the break statement will make us jump out of a while-block.) The program execution moves back to the line that had called the function.

You can also use the return keyword by itself just to break out of the function, just like the break keyword will break out of a while loop.

Variable Scope

Just like the values in our program's variables are forgotten after the program ends, variables created inside the function are forgotten after the execution leaves the function. Not only that, but when execution is inside the function, we cannot change the variables outside of the function, or variables inside other functions. The variable's scope is this range that variables can be modified in. The only variables that we can use inside a function are the ones we create inside of the function (or the parameter variables, described later). That is, the scope of the variable is inside in the function's block. The scope of variables created outside of functions is outside of all functions in the program.

Not only that, but if we have a variable named spam created outside of a function, and we create a variable named spam inside of the function, the Python interpreter will consider them to be two separate variables. That means we can change the value of spam inside the function, and this will not change the spam variable that is outside of the function. This is because these variables have different scopes, the global scope and the local scope.

Global Scope and Local Scope

We have names for these scopes. The scope outside of all functions is called the global scope. The scope inside of a function is called the local scope. The entire program has only one global scope, and each function has a local scope of its own.

Variables defined in the global scope can be read outside and inside functions, but can only be modified outside of all functions. Variables defined in a function's local scope can only be read or modified inside that function.

Specifically, we can read the value of global variables from the local scope, but attempting to change the value in a global variable from the local scope will leave the global variable unchanged. What Python actually does is create a local variable with the same name as the global variable. But Python will consider these to be two different variables.

Look at this example to see what happens when you try to change a global variable from inside a local scope. Remember that the code in the funky() function isn't run until the funky() function is called. The comments explain what is going on:

# This block doesn't run until funky() is called: 
def funky():
     # We read the global variable's value: 
     print(spam)   # 42
     # We create a local variable named "spam"
     # instead of changing the value of the global
     # variable "spam": 
     spam = 99
     # The name "spam" now refers to the local
     # variable only for the rest of this
     # function: 
     print(spam) # 99

# A global variable named "spam": 
spam = 42

# Call the funky() function: 
# The global variable was not changed in funky(): 
print(spam)  # 42

It is important to know when a variable is defined because that is how we know the variable's scope. A variable is defined the first time we use it in an assignment statement. When the program first executes the line:

12 .    cave = ' '

...the variable cave is defined.

If we call the chooseCave() function twice, the value stored in the variable the first time won't be remember the second time around. This is because when the execution left the chooseCave() function (that is, left chooseCave()'s local scope), the cave variable was forgotten and destroyed. But it will be defined again when we call the function a second time because line 12 will be executed again.

The important thing to remember is that the value of a variable in the local scope is not remembered in between function calls.

Defining the checkCave() Function

19. def checkCave(chosenCave):

Now we are defining yet another function named checkCave(). Notice that we put the text chosenCave in between the parentheses. The variable names in between the parentheses are called parameters.

Remember, for some functions like for the str() or randint(), we would pass an argument in between the parentheses:

>>> str(5)
>>> random.randint(1, 20)

When we call checkCave(), we will also pass one value to it as an argument. When execution moves inside the checkCave() function, a new variable named chosenCave will be assigned this value. This is how we pass variable values to functions since functions cannot read variables outside of the function (that is, outside of the function's local scope). Parameters are local variables that get defined when a function is called. The value stored in the parameter is the argument that was passed in the function call.


For example, here is a short program that demonstrates parameters. Imagine we had a short program that looked like this:

def sayHello(name):
print('Hello, ' + name)

print('Say hello to Alice.')
fizzy = 'Alice'
print('Do not forget to say hello to Bob.')

If we run this program, it would look like this:

Say hello to Alice.
Hello, Alice
Do not forget to say hello to Bob.
Hello, Bob

This program calls a function we have created, csayHello() and first passes the value in the fizzy variable as an argument to it. (We stored the string 'Alice' in fizzy.) Later, the program calls the sayHello() function again, passing the string 'Bob' as an argument.

The value in the fizzy variable and the string 'Bob' are arguments. The name variable in sayHello() is a parameter. The difference between arguments and parameters is that arguments are the values passed in a function call, and parameters are the local variables that store the arguments. It might be easier to just remember that the thing in between the parentheses in the def statement is an parameter, and the thing in between the parentheses in the function call is an argument.

We could have just used the fizzy variable inside the sayHello() function instead of using a parameter. (This is because the local scope can still see variables in the global scope.) But then we would have to remember to assign the fizzy variable a string each time before we call the sayHello() function. Parameters make our programs simpler. Look at this code:

def sayHello():
    print('Hello, ' + fizzy)

print('Say hello to Alice.')
fizzy = 'Alice'
print('Do not forget to say hello to Bob.')

When we run this code, it looks like this:

Say hello to Alice.
Hello, Alice
Do not forget to say hello to Bob.
Hello, Alice

This program's sayHello() function does not have a parameter, but uses the global variable fizzy directly. Remember that you can read global variables inside of functions, you just can't modify the value stored in the variable.

Without parameters, we have to remember to set the fizzy variable before calling sayHello(). In this program, we forgot to do so, so the second time we called sayHello() the value of fizzy was still 'Alice'. Using parameters makes function calling simpler to do, especially when our programs are very big and have many functions.

Local Variables and Global Variables with the Same Name

Now look at the following program, which is a bit different. To make it clear to see, the global variable has been bordered with a line, and the local variable has been bordered with dots;.

def spam(ImyName!):
    print('Hello, ' + ImyName!)
    ImyName! = 'Waffles'
    print('Your new name is ' + ImyName!)

myName = 'Albert'
print('Howdy, ' + myName)

If we run this program, it would look like this:

Hello, Albert
Your new name is Waffles
Howdy, Albert

This program defines a new variable called myName and stores the string 'Albert' in it. Then the program calls the spam() function, passing the value in myName as an argument. The execution moves to the spam() function. The parameter in spam() is also named myName, and has the argument value assigned to it. Remember, the myName inside the spam() function (the local scope) is considered a different variable than the myName variable outside the function (the global scope).

The function then prints 'Hello, Albert', and then on the next line changes the value in myName to 'Waffles'. Remember, this only changes the local myName variable that is inside the function. The global myName variable that is outside the function still has the value 'Albert' stored in it.

The function now prints out 'Your new name is Waffles', because the myName variable in the local scope has changed to 'Waffles'. The execution has reached the end of the function, so it jumps back down to where the function call was. The local myName is destroyed and forgotten. The next line after that is print('Howdy, ' + myName), which will display Howdy, Albert.

Remember, the myName outside of functions (that is, in the global scope) still has the value 'Albert', not 'Waffles'. This is because the myName in the global scope and the myName in spam()'s local scope are different variables, even though they have the same name.

Where to Put Function Definitions

A function's definition (where we put the def statement and the def-block) has to come before you call the function. This is like how you must assign a value to a variable before you can use the variable. If you put the function call before the function definition, you will get an error. Look at this code:

def sayGoodBye():
print('Good bye!')

If you try to run it, Python will give you an error message that looks like this:

Traceback (most recent call last):
File "C:\Python31\foo.py", line 1, in <module> sayGoodBye()
NameError: name 'sayGoodBye' is not defined

To fix this, put the function definition before the function call:

def sayGoodBye():
print('Good bye!')
< Лекция 5 || Лекция 6: 123 || Лекция 7 >
alex nab
alex nab
Россия, мск
Сергей Хвощев
Сергей Хвощев
Россия, Ленинград, ВВМУ им Фрунзе, 1980