Jump to content

Archive:Think Python/Functions

From IdeaWazaWiki
Revision as of 22:43, 15 September 2008 by wikademia>Whiteknight (Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"

           "http://www.w3.org/TR/REC-html40/loose.dtd">

<HTML> <HEAD>

<META http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="book.css"> <TITLE>Functions</TITLE> </HEAD> <BODY > <A HREF="book003.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book005.html"><IMG SRC="next_motif.gif" ALT="Next"></A>


<A NAME="htoc28">Chapter 3</A>  Functions

<A NAME="funcchap"></A>

<A NAME="toc24"></A><A NAME="htoc29">3.1</A>  Function calls

<A NAME="functionchap"></A>

<A NAME="@default185"></A>

In the context of programming, a function is a named sequence of

statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name.

We have already seen one example of a function call:

<FONT COLOR=blue><FONT SIZE=4>>>> type(32)
<type 'int'>
</FONT></FONT>

The name of the function is type. The expression in parentheses

is called the argument of the function. The result, for this

function, is the type of the argument.

<A NAME="@default186"></A>

It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value.

<A NAME="@default187"></A> <A NAME="@default188"></A>

<A NAME="toc25"></A><A NAME="htoc30">3.2</A>  Type conversion functions

<A NAME="@default189"></A>

<A NAME="@default190"></A>

Python provides built-in functions that convert values

from one type to another. The int function takes any value and

converts it to an integer, if it can, or complains otherwise:

<A NAME="@default191"></A> <A NAME="@default192"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
</FONT></FONT>

int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:

<FONT COLOR=blue><FONT SIZE=4>>>> int(3.99999)
3
>>> int(-2.3)
-2
</FONT></FONT>

float converts integers and strings to floating-point numbers:

<A NAME="@default193"></A> <A NAME="@default194"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> float(32)
32.0
>>> float('3.14159')
3.14159
</FONT></FONT>

Finally, str converts its argument to a string:

<A NAME="@default195"></A> <A NAME="@default196"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
</FONT></FONT>

<A NAME="toc26"></A><A NAME="htoc31">3.3</A>  Math functions

<A NAME="@default197"></A>

<A NAME="@default198"></A>

Python has a math module that provides most of the familiar

mathematical functions. A module is a file that contains a

collection of related functions.

<A NAME="@default199"></A> <A NAME="@default200"></A>

Before we can use the module, we have to import it:

<FONT COLOR=blue><FONT SIZE=4>>>> import math
</FONT></FONT>

This statement creates a module object named math. If you print the module object, you get some information about it:

<FONT COLOR=blue><FONT SIZE=4>>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
</FONT></FONT>

The module object contains the functions and variables defined in the

module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also

known as a period). This format is called dot notation.

<A NAME="@default201"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)

>>> radians = 0.7
>>> height = math.sin(radians)
</FONT></FONT>

The first example computes the logarithm base 10 of the

signal-to-noise ratio. The math module also provides a

function called log that computes logarithms base e.

<A NAME="@default202"></A>

<A NAME="@default203"></A> <A NAME="@default204"></A> <A NAME="@default205"></A> <A NAME="@default206"></A>

<A NAME="@default207"></A>

The second example finds the sine of radians. The name of the

variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2

π:

<FONT COLOR=blue><FONT SIZE=4>>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
</FONT></FONT>

The expression math.pi gets the variable pi from the math

module. The value of this variable is an approximation

of π, accurate to about 15 digits.

<A NAME="@default208"></A>

If you know

your trigonometry, you can check the previous result by comparing it to

the square root of two divided by two:

<A NAME="@default209"></A> <A NAME="@default210"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> math.sqrt(2) / 2.0
0.707106781187
</FONT></FONT>

<A NAME="toc27"></A><A NAME="htoc32">3.4</A>  Composition

<A NAME="@default211"></A>

So far, we have looked at the elements of a program—variables,

expressions, and statements—in isolation, without talking about how to

combine them.

One of the most useful features of programming languages is their

ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression,

including arithmetic operators:

<FONT COLOR=blue><FONT SIZE=4>x = math.sin(degrees / 360.0 * 2 * math.pi)
</FONT></FONT>

And even function calls:

<FONT COLOR=blue><FONT SIZE=4>x = math.exp(math.log(x+1))
</FONT></FONT>

Almost anywhere you can put a value, you can put an arbitrary

expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left

side is a syntax error<A NAME="text5" HREF="#note5">1</A>.

<FONT COLOR=blue><FONT SIZE=4>>>> minutes = hours * 60                 # right
>>> hours * 60 = minutes                 # wrong!
SyntaxError: can't assign to operator
</FONT></FONT>

<A NAME="@default212"></A> <A NAME="@default213"></A>

<A NAME="toc28"></A><A NAME="htoc33">3.5</A>  Adding new functions

So far, we have only been using the functions that come with Python,

but it is also possible to add new functions. A function definition specifies the name of a new function and

the sequence of statements that execute when the function is called.

<A NAME="@default214"></A>

<A NAME="@default215"></A>

<A NAME="@default216"></A>

Here is an example:

<FONT COLOR=blue><FONT SIZE=4>def print_lyrics():
    print "I'm a lumberjack, and I'm okay."
    print "I sleep all night and I work all day."
</FONT></FONT>

def is a keyword that indicates that this is a function

definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same

name.

<A NAME="@default217"></A>

<A NAME="@default218"></A>

<A NAME="@default219"></A>

The empty parentheses after the name indicate that this function doesn’t take any arguments.

<A NAME="@default220"></A>

<A NAME="@default221"></A> <A NAME="@default222"></A> <A NAME="@default223"></A>

<A NAME="@default224"></A>

The first line of the function definition is called the header;

the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces (see Section <A HREF="#editor">3.13</A>). The body can contain

any number of statements.

The strings in the print statements are enclosed in double

quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where

a single quote (which is also an apostrophe) appears in the string.

<A NAME="@default225"></A>

If you type a function definition in interactive mode, the interpreter

prints ellipses (...) to let you know that the definition

isn’t complete:

<FONT COLOR=blue><FONT SIZE=4>>>> def print_lyrics():
...     print "I'm a lumberjack, and I'm okay."
...     print "I sleep all night and I work all day."
...
</FONT></FONT>

To end the function, you have to enter an empty line (this is not necessary in a script).

Defining a function creates a variable with the same name.

<FONT COLOR=blue><FONT SIZE=4>>>> print print_lyrics
<function print_lyrics at 0xb7e99e9c>
>>> print type(print_lyrics)
<type 'function'>
</FONT></FONT>

The value of print_lyrics is a function object, which has type 'function'.

<A NAME="@default226"></A> <A NAME="@default227"></A>

The syntax for calling the new function is the same as for built-in functions:

<FONT COLOR=blue><FONT SIZE=4>>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
</FONT></FONT>

Once you have defined a function, you can use it inside another

function. For example, to repeat the previous refrain, we could write

a function called repeat_lyrics:

<FONT COLOR=blue><FONT SIZE=4>def repeat_lyrics():
    print_lyrics()
    print_lyrics()
</FONT></FONT>

And then call repeat_lyrics:

<FONT COLOR=blue><FONT SIZE=4>>>> repeat_lyrics()

I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day.

</FONT></FONT>

But that’s not really how the song goes.

<A NAME="toc29"></A><A NAME="htoc34">3.6</A>  Definitions and uses

<A NAME="@default228"></A>

Pulling together the code fragments from the previous section, the whole program looks like this:

<FONT COLOR=blue><FONT SIZE=4>def print_lyrics():
    print "I'm a lumberjack, and I'm okay."
    print "I sleep all night and I work all day."

def repeat_lyrics():
    print_lyrics()
    print_lyrics()

repeat_lyrics()
</FONT></FONT>

This program contains two function definitions: print_lyrics and

repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and

the function definition generates no output.

<A NAME="@default229"></A>

As you might expect, you have to create a function before you can

execute it. In other words, the function definition has to be

executed before the first time it is called.

Exercise 1  

Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.

Exercise 2  

Move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program?

<A NAME="toc30"></A><A NAME="htoc35">3.7</A>  Flow of execution

<A NAME="@default230"></A>

In order to ensure that a function is defined before its first use,

you have to know the order in which statements are executed, which is

called the flow of execution.

Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the

program, but remember that statements inside the function are not

executed until the function is called.

A function call is like a detour in the flow of execution. Instead of

going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back

to pick up where it left off.

That sounds simple enough, until you remember that one function can

call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet

another function!

Fortunately, Python is good at keeping track of where it is, so each

time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program,

it terminates.

What’s the moral of this sordid tale? When you read a program, you

don’t always want to read from top to bottom. Sometimes it makes

more sense if you follow the flow of execution.

<A NAME="toc31"></A><A NAME="htoc36">3.8</A>  Parameters and arguments

<A NAME="parameters"></A> <A NAME="@default231"></A> <A NAME="@default232"></A> <A NAME="@default233"></A>

<A NAME="@default234"></A>

Some of the built-in functions we have seen require arguments. For

example, when you call math.sin you pass a number as an argument. Some functions take more than one argument:

math.pow takes two, the base and the exponent.

Inside the function, the arguments are assigned to

variables called parameters. Here is an example of a

user-defined function that takes an argument:

<A NAME="@default235"></A>

<FONT COLOR=blue><FONT SIZE=4>def print_twice(bruce):
    print bruce
    print bruce
</FONT></FONT>

This function assigns the argument to a parameter

named bruce. When the function is called, it prints the value of

the parameter (whatever it is) twice.

This function works with any value that can be printed.

<FONT COLOR=blue><FONT SIZE=4>>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
</FONT></FONT>

The same rules of composition that apply to built-in functions also

apply to user-defined functions, so we can use any kind of expression

as an argument for print_twice:

<A NAME="@default236"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
</FONT></FONT>

The argument is evaluated before the function is called, so

in the examples the expressions 'Spam '*4 and

math.cos(math.pi) are only evaluated once.

<A NAME="@default237"></A>

You can also use a variable as an argument:

<FONT COLOR=blue><FONT SIZE=4>>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
</FONT></FONT>

The name of the variable we pass as an argument (michael) has

nothing to do with the name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller);

here in print_twice, we call everybody bruce.

<A NAME="toc32"></A><A NAME="htoc37">3.9</A>  Variables and parameters are local

<A NAME="@default238"></A>

<A NAME="@default239"></A>

When you create a variable inside a function, it is local,

which means that it only

exists inside the function. For example:

<A NAME="@default240"></A>

<FONT COLOR=blue><FONT SIZE=4>def cat_twice(part1, part2):
    cat = part1 + part2
    print_twice(cat)
</FONT></FONT>

This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:

<A NAME="@default241"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
</FONT></FONT>

When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception:

<A NAME="@default242"></A> <A NAME="@default243"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> print cat
NameError: name 'cat' is not defined
</FONT></FONT>

Parameters are also local.

For example, outside print_twice, there is no

such thing as bruce.

<A NAME="@default244"></A>

<A NAME="toc33"></A><A NAME="htoc38">3.10</A>  Stack diagrams

<A NAME="stackdiagram"></A> <A NAME="@default245"></A> <A NAME="@default246"></A>

<A NAME="@default247"></A>

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.

<A NAME="@default248"></A> <A NAME="@default249"></A>

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:

<IMG SRC="book004.png">

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__.

For example, if you try to access cat from within print_twice, you get a NameError:

<FONT COLOR=blue><FONT SIZE=4>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
</FONT></FONT>

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.

<A NAME="@default250"></A>

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.

<A NAME="toc34"></A><A NAME="htoc39">3.11</A>  Fruitful functions and void functions

<A NAME="@default251"></A>

<A NAME="@default252"></A> <A NAME="@default253"></A>

<A NAME="@default254"></A>

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:

<FONT COLOR=blue><FONT SIZE=4>x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
</FONT></FONT>

When you call a function in interactive mode, Python displays the result:

<FONT COLOR=blue><FONT SIZE=4>>>> math.sqrt(5)
2.2360679774997898
</FONT></FONT>

But in a script, if you call a fruitful function all by itself, the return value is lost forever!

<FONT COLOR=blue><FONT SIZE=4>math.sqrt(5)
</FONT></FONT>

This script computes the square root of 5, but since it doesn’t store or display the result, it is not very useful.

<A NAME="@default255"></A> <A NAME="@default256"></A>

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.

<A NAME="@default257"></A> <A NAME="@default258"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None
</FONT></FONT>

The value None is not the same as the string 'None'. It is a special value that has its own type:

<FONT COLOR=blue><FONT SIZE=4>>>> print type(None)
<type 'NoneType'>
</FONT></FONT>

The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.

<A NAME="toc35"></A><A NAME="htoc40">3.12</A>  Why functions?

<A NAME="@default259"></A>

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.

<A NAME="toc36"></A><A NAME="htoc41">3.13</A>  Debugging

<A NAME="editor"></A>

<A NAME="@default260"></A>

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.

<A NAME="@default261"></A>

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 environments 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!

<A NAME="toc37"></A><A NAME="htoc42">3.14</A>  Glossary

function:
A named sequence of statements that performs some

useful operation. Functions may or may not take arguments and may or may not produce a result.

<A NAME="@default262"></A>
function definition:
A statement that creates a new function, specifying its name, parameters, and the statements it executes. <A NAME="@default263"></A>
function object:
A value created by a function definition. The name of the function is a variable that refers to a function object. <A NAME="@default264"></A>
header:
The first line of a function definition. <A NAME="@default265"></A>
body:
The sequence of statements inside a function definition. <A NAME="@default266"></A>
parameter:
A name used inside a function to refer to the value passed as an argument. <A NAME="@default267"></A>
function call:
A statement that executes a function. It consists of the function name followed by an argument list. <A NAME="@default268"></A>
argument:
A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function. <A NAME="@default269"></A>
local variable:
A variable defined inside a function. A local variable can only be used inside its function. <A NAME="@default270"></A>
return value:
The result of a function. If a function call is used as an expression, the return value is the value of the expression. <A NAME="@default271"></A>
fruitful function:
A function that returns a value. <A NAME="@default272"></A>
void function:
A function that doesn’t return a value. <A NAME="@default273"></A>
module:
A file that contains a collection of related functions and other definitions. <A NAME="@default274"></A>
import statement:
A statement that reads a module file and creates a module object. <A NAME="@default275"></A> <A NAME="@default276"></A>
module object:
A value created by an import statement that provides access to the values defined in a module. <A NAME="@default277"></A>
dot notation:
The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name. <A NAME="@default278"></A>
composition:
Using an expression as part of a larger expression, or a statement as part of a larger statement. <A NAME="@default279"></A>
flow of execution:
The order in which statements are executed during a program run. <A NAME="@default280"></A>
stack diagram:
A graphical representation of a stack of functions, their variables, and the values they refer to. <A NAME="@default281"></A>
frame:
A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function. <A NAME="@default282"></A> <A NAME="@default283"></A>
traceback:
A list of the functions that are executing, printed when an exception occurs. <A NAME="@default284"></A>

<A NAME="toc38"></A><A NAME="htoc43">3.15</A>  Exercises

Exercise 3  

<A NAME="@default285"></A> <A NAME="@default286"></A>

Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5.

Write a function named right_justify that takes a string

named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70

of the display.

<EM><FONT COLOR=blue><FONT SIZE=4>>>> right_justify('allen')
                                                                 allen
</FONT></FONT></EM>
Exercise 4  

<A NAME="@default287"></A>

<A NAME="@default288"></A>

A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:

<EM><FONT COLOR=blue><FONT SIZE=4>def do_twice(f):
    f()
    f()
</FONT></FONT></EM>

Here’s an example that uses do_twice to call a function named print_spam twice.

<EM><FONT COLOR=blue><FONT SIZE=4>def print_spam():
    print 'spam'

do_twice(print_spam)
</FONT></FONT></EM>
  1. Type this example into a script and test it.
  2. Modify do_twice so that it takes two arguments, a

    function object and a value, and calls the function twice,

    passing the value as an argument.
  3. Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
  4. Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
  5. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.

You can see my solution at thinkpython.com/code/do_four.py.

Exercise 5  

This exercise<A NAME="text6" HREF="#note6">2</A> can be done using only the statements and other features we have learned so

far.

<A NAME="@default289"></A>

  1. Write a function that draws a grid like the following:
    <EM><FONT COLOR=blue><FONT SIZE=4>+ - - - - + - - - - +
    |         |         |
    |         |         |
    |         |         |
    |         |         |
    + - - - - + - - - - +
    |         |         |
    |         |         |
    |         |         |
    |         |         |
    + - - - - + - - - - +
    </FONT></FONT></EM>

    Hint: to print more than one value on a line, you can print a comma-separated sequence:

    <EM><EM><FONT COLOR=blue><FONT SIZE=4>print '+', '-'
    </FONT></FONT></EM></EM>

    If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.

    <EM><EM><FONT COLOR=blue><FONT SIZE=4>print '+', 
    print '-'
    </FONT></FONT></EM></EM>

    The output of these statements is '+ -'.

    A print statement all by itself ends the current line and goes to the next line.

  2. Use the previous function to draw a similar grid with four rows and four columns.

You can see my solution at thinkpython.com/code/grid.py.


<A NAME="note5" HREF="#text5">1</A>
We will see exceptions to this rule later.
<A NAME="note6" HREF="#text6">2</A>
Based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly (1997)

<A HREF="book003.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book005.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>