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

Dragon Realm

< Лекция 5 || Лекция 6: 123 || Лекция 7 >
Аннотация: Creating our own functions with the def keyword. Variable scope (Global and Local). Parameters and Arguments.

Topics Covered In This Chapter:

  • The time module.
  • The time.sleep() function.
  • The return keyword.
  • Creating our own functions with the def keyword.
  • The and and or and not boolean operators.
  • Truth tables
  • Variable scope (Global and Local)
  • Parameters and Arguments
  • Flow charts

Introducing Functions

We've already used two functions in our previous programs: input() and print(). In our previous programs, we have called these functions to execute the code that is inside these functions. In this chapter, we will write our own functions for our programs to call. A function is like a mini-program that is inside of our program. Many times in a program we want to run the exact same code multiple times. Instead of typing out this code several times, we can put that code inside a function and call the function several times. This has the added benefit that if we make a mistake, we only have one place in the code to change it.

The game we will create to introduce functions is called "Dragon Realm", and lets the player make a guess between two caves which randomly hold treasure or certain doom.

How to Play "Dragon Realm"

In this game, the player is in a land full of dragons. The dragons all live in caves with their large piles of collected treasure. Some dragons are friendly, and will share their treasure with you. Other dragons are greedy and hungry, and will eat anyone who enters their cave. The player is in front of two caves, one with a friendly dragon and the other with a hungry dragon. The player is given a choice between the two.

Open a new file editor window by clicking on the File menu, then click on New Window. In the blank window that appears type in the source code and save the source code as dragon.py. Then run the program by pressing F5.

Sample Run of Dragon Realm

You are in a land full of dragons. In front of you, you see two caves. 
In one cave, the dragon is friendly and will share his treasure with you. 
The other dragon is greedy and hungry, and will eat you on sight.
Which cave will you go into? (1 or 2)
1
You approach the cave...
It is dark and spooky...
A large dragon jumps out in front of you! He opens his jaws
and...
Gobbles you down in one bite!
Do you want to play again? (yes or no)
no

Dragon Realm's Source Code

Here is the source code for the Dragon Realm game. Typing in the source code is a great way to get used to the code. But if you don't want to do all this typing, you can download the source code from this book's website at the URL http://inventwithpython.com/chapter6. There are instructions on the website that will tell you how to download and open the source code file. You can use the online diff tool on the website to check for any mistakes in your code.

One thing to know as you read through the code below: The blocks that follow the def lines define a function, but the code in that block does not run until the function is called. The code does not execute each line in this program in top down order. This will be explained in more detail later in this chapter.

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.

dragon.py

This code can be downloaded from http://inventwithpyt.hon.com/dragon.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.  import random
2.  import time 3 .
4. def displayIntro () :
5.     print('You are on a planet full of dragons. In front of you,')
6.     print('you see two caves. In one cave, the dragon is friendly')
7.     print('and will share his treasure with you. The other dragon')
8.     print('is greedy and hungry, and will eat you on sight.')
9.     print() 10 .
11. def chooseCave() : 12 .    cave = ' '
13.     while cave != '1' and cave != '2':
14.         print('Which cave will you go into? (1 or 2)')
15.           cave = input () 16 .
17.             return cave
18 .
19.   def checkCave(chosenCave):
20.             print('You approach the cave...')
21.     time.sleep(2)
22.     print('It is dark and spooky...')
23.     time.sleep(2)
24.      print('A large dragon jumps out in front of you! He opens his jaws and...')
25.             print()
26.             time.sleep(2)
27.
28.            friendlyCave = random.randint(1, 2)
29.
30.      if chosenCave == str(friendlyCave):
31.         print('Gives you his treasure!')
32.     else:
33.         print('Gobbles you down in one bite!') 34 .
35. playAgain = 'yes'
36. while playAgain == 'yes' or playAgain == 'y': 37 .
38.     displayIntro()
39.
40.     caveNumber = chooseCave()
41.
42.     checkCave(caveNumber) 43 .
44.     print('Do you want to play again? (yes or no)')
45.     playAgain = input()

How the Code Works

Let's look at the source code in more detail.

1.  import random
2.  import time

Here we have two import statements. We import the random module like we did in the Guess the Number game. In Dragon Realm, we will also want some time-related functions that the time module includes, so we will import that as well.

Defining the displayIntro() Function

4 . def displayIntro():
5 . print('You are on a planet full of dragons. In front of you,')
6 . print('you see two caves. In one cave, the dragon is friendly')
7 . print('and will share his treasure with you. The other dragon')
8 . print ( 'is greedy and hungry, and will eat you on sight.')
9 . print()

Figure 6.1 shows a new type of statement, the def statement. The def statement is made up of the def keyword, followed by a function name with parentheses, and then a colon (the : sign). There is a block after the statement called the def-block.

Parts of a def statement.

Рис. 6.1. Parts of a def statement.

def Statements

The def statement isn't a call to a function named displayIntro(). Instead, the def statement means we are creating, or defining, a new function that we can call later in our program. After we define this function, we can call it the same way we call other functions. When we call this function, the code inside the def-block will be executed.

We also say we define variables when we create them with an assignment statement. The code spam = 42 defines the variable spam.

Remember, the def statement doesn't execute the code right now, it only defines what code is executed when we call the displayIntro() function later in the program. When the program's execution reaches a def statement, it skips down to the end of the def-block. We will jump back to the top of the def-block when the displayIntro() function is called. It will then execute all the print() statements inside the def-block. So we call this function when we want to display the "You are on a planet full of dragons..." introduction to the user.

When we call the displayIntro() function, the program's execution jumps to the start of the function on line 5. When the function's block ends, the program's execution returns to the line that called the function.

We will explain all of the functions that this program will use before we explain the main part of the program. It may be a bit confusing to learn the program out of the order that it executes. But just keep in mind that when we define the functions they just silently sit around waiting to be called into action.

Defining the chooseCave() Function

11. def chooseCave() :

Here we are defining another function called chooseCave. The code in this function will prompt the user to select which cave they should go into.

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

Inside the chooseCave() function, we create a new variable called cave and store a blank string in it. Then we will start a while loop. This while statement's condition contains a new operator we haven't seen before called and. Just like the - or * are mathematical operators, and == or != are comparison operators, the and operator is a boolean operator.

Boolean Operators

Boolean logic deals with things that are either true or false. This is why the boolean data type only has two values, True and False. Boolean statements are always either true or false. If the statement is not true, then it is false. And if the statement is not false, then it is true.

Boolean operators compare two different boolean values and evaluate to a single boolean value. Do you remember how the * operator will combine two integer values and produce a new integer value (the product of the two original integers)? And do you also remember how the + operator can combine two strings and produce a new string value (the concatenation of the two original strings)? The and boolean operator combines two boolean values to produce a new boolean value. Here's how the and operator works.

Think of the sentence, "Cats have whiskers and dogs have tails." This sentence is true, because "cats have whiskers" is true and "dogs have tails" is also true.

But the sentence, "Cats have whiskers and dogs have wings." would be false. Even though "cats have whiskers" is true, dogs do not have wings, so "dogs have wings" is false. The entire sentence is only true if both parts are true because the two parts are connected by the word "and." If one or both parts are false, then the entire sentence is false.

The and operator in Python works this way too. If the boolean values on both sides of the and keyword are True, then the expression with the and operator evaluates to True. If either of the boolean values are False, or both of the boolean values are False, then the expression evaluates to False.

Evaluating an Expression That Contains Boolean Operators

So let's look at line 13 again:

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

This condition is made up of two expressions connected by the and boolean operator. We first evaluate these expressions to get their boolean (that is, True or False) values. Then we evaluate the boolean values with the and operator.

The string value stored in cave when we first execute this while statement is the blank string, ''. The blank string does not equal the string '1', so the left side evaluates to True. The blank string also does not equal the string '2', so the right side evaluates to True. So the condition then turns into True and True. Because both boolean values are True, the condition finally evaluates to True. And because the while statement's condition is True, the program execution enters the while-block.

This is all done by the Python interpreter, but it is important to understand how the interpreter does this. This picture shows the steps of how the interpreter evaluates the condition (if the value of cave is the blank string):

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

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

while True and '' != '2' :

while True and True :

while True :

Experimenting with the and and or Operators

Try typing the following into the interactive shell:

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False

There are two other boolean operators. The next one is the or operator. The or operator works similar to the and, except it will evaluate to True if either of the two boolean values are True. The only time the or operator evaluates to False is if both of the boolean values are False.

The sentence "Cats have whiskers or dogs have wings." is true. Even though dogs don't have wings, when we say "or" we mean that one of the two parts is true. The sentence "Cats have whiskers or dogs have tails." is also true. (Most of the time when we say "this OR that", we mean one thing is true but the other thing is false. In programming, "or" means that either of the things are true, or maybe both of the things are true.)

Try typing the following into the interactive shell:

>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
< Лекция 5 || Лекция 6: 123 || Лекция 7 >
Patryk Jasiński
Patryk Jasiński
Польша
Юрий Гоголев
Юрий Гоголев
Россия, Тула, ТулГУ, 2002