This page intentionally left blank Python for Software Design


VARIABLES AND PARAMETERS ARE LOCAL When you create a variable inside a function, it is local



tải về 1.38 Mb.
Chế độ xem pdf
trang16/83
Chuyển đổi dữ liệu13.08.2023
Kích1.38 Mb.
#55046
1   ...   12   13   14   15   16   17   18   19   ...   83
- Python for Software Design How to Think Like a Computer Scientist-Cambridge University Press (2009)

3.9
VARIABLES AND PARAMETERS ARE LOCAL
When you create a variable inside a function, it is local, which means that it only
exists inside the function. For example:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
This function takes two arguments, concatenates them, and prints the result twice.
Here is an example that uses it:
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.


3.10 Stack Diagrams
29
When cat_twice terminates, the variable cat is destroyed. If we try to print it, we
get an exception:
>>> print cat
NameError: name 'cat' is not defined
Parameters are also local. For example, outside print_twice, there is no such thing
as bruce.
3.10
STACK DIAGRAMS
To keep track of which variables can be used where, it is sometimes useful to draw a
stack diagram. Like state diagrams, stack diagrams show the value of each variable,
but they also show the function each variable belongs to.
Each function is represented by a frame. A frame is a box with the name of a function
beside it and the parameters and variables of the function inside it. The stack diagram
for the previous example looks like this:
line1
line2
’tiddle bang.’
part1
part2
cat
bruce
’Bing tiddle ’
’Bing tiddle ’
’tiddle bang.’
’Bing tiddle tiddle bang.’
’Bing tiddle tiddle bang.’
__main__
cat_twice
print_twice
The frames are arranged in a stack that indicates which function called which, and
so on. In this example, print_twice was called by cat_twice, and cat_twice was
called by __main__, which is a special name for the topmost frame. When you create
a variable outside of any function, it belongs to __main__.
Each parameter refers to the same value as its corresponding argument. So, part1
has the same value as line1, part2 has the same value as line2, and bruce has the
same value as cat.
If an error occurs during a function call, Python prints the name of the function, and
the name of the function that called it, and the name of the function that called that,
all the way back to __main__.


30
Functions
For example, if you try to access cat from within print_twice, you get a NameError:
Traceback (innermost last):
File "test.py", line 13, in __main__
cat_twice(line1, line2)
File "test.py", line 5, in cat_twice
print_twice(cat)
File "test.py", line 9, in print_twice
print cat
NameError: name 'cat' is not defined
This list of functions is called a traceback. It tells you what program file the error
occurred in, and what line, and what functions were executing at the time. It also
shows the line of code that caused the error.
The order of the functions in the traceback is the same as the order of the frames in
the stack diagram. The function that is currently running is at the bottom.
3.11
FRUITFUL FUNCTIONS AND VOID FUNCTIONS
Some of the functions we are using, such as the math functions, yield results; for lack
of a better name, I call them fruitful functions. Other functions, like print_twice,
perform an action but don’t return a value. They are called void functions.
When you call a fruitful function, you almost always want to do something with the
result; for example, you might assign it to a variable or use it as part of an expression:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt(5)
2.2360679774997898
But in a script, if you call a fruitful function all by itself, the return value is lost
forever!
math.sqrt(5)


3.13 Debugging
31
This script computes the square root of 5, but since it doesn’t store or display the
result, it is not very useful.
Void functions might display something on the screen or have some other effect, but
they don’t have a return value. If you try to assign the result to a variable, you get a
special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None
The value None is not the same as the string 'None'. It is a special value that has its
own type:
>>> print type(None)

The functions we have written so far are all void. We will start writing fruitful
functions in a few chapters.
3.12
WHY FUNCTIONS?
It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:

Creating a new function gives you an opportunity to name a group of statements,
which makes your program easier to read and debug.

Functions can make a program smaller by eliminating repetitive code. Later, if
you make a change, you only have to make it in one place.

Dividing a long program into functions allows you to debug the parts one at a
time and then assemble them into a working whole.

Well-designed functions are often useful for many programs. Once you write and
debug one, you can reuse it.
3.13
DEBUGGING
If you are using a text editor to write your scripts, you might run into problems with
spaces and tabs. The best way to avoid these problems is to use spaces exclusively
(no tabs). Most text editors that know about Python do this by default, but some
don’t.


32
Functions
Tabs and spaces are usually invisible, which makes them hard to debug, so try to find
an editor that manages indentation for you.
Also, don’t forget to save your program before you run it. Some development envi-
ronments do this automatically, but some don’t. In that case the program you are
looking at in the text editor is not the same as the program you are running.
Debugging can take a long time if you keep running the same, incorrect, program
over and over!
Make sure that the code you are looking at is the code you are running. If you’re not
sure, put something like print 'hello' at the beginning of the program and run it
again. If you don’t see hello, you’re not running the right program!

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   12   13   14   15   16   17   18   19   ...   83




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương