Python For Rookies A First Course in Pro
Python For Rookies A First Course in Pro
Printer
C & C Offset Printing Co
Ltd, China
Copyright © 2008 Thomson All rights reserved by Thomson While the publisher has taken
Learning (EMEA) Ltd Learning (EMEA) Ltd 2008. all reasonable care in the
The text of this publication, or preparation of this book the
The Thomson logo is a any part thereof, may not be publisher makes no
registered trademark used reproduced or transmitted in representation, express or
herein under licence. any form or by any means, implied, with regard to the
electronic or mechanical, accuracy of the information
For more information, contact including photocopying, contained in this book and
Thomson Learning, High recording, storage in an cannot accept any legal
Holborn House; 50–51 Bedford information retrieval system, or responsibility or liability for
Row, London WC1R 4LR or otherwise, with the exception any errors or omissions from
visit us on the World Wide Web of any material supplied the book or the consequences
at: http://www. specifically for the purpose of thereof.
thomsonlearning.co.uk being entered and executed on
a computer system for the Products and services that are
ISBN 978-1-84480-701-7 exclusive use of the reader, referred to in this book may be
without prior permission of the either trademarks and/or
publisher. registered trademarks of their
respective owners. The
Code for all examples in the publisher and author/s make
book is available for download no claim to these trademarks.
under the GNU General Public
License (GPL), see http://www. British Library
gnu.org/copyleft/gpl.html for Cataloguing-in-Publication
further information. Data A catalogue record for
this book is available from the
Every effort has been made to British Library.
trace all the copyright holders
but if any have been
inadvertently overlooked, the
publisher will be pleased to
make the necessary
arrangements at the first
opportunity. Please contact the
publisher directly.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Getting Started
1
Learning Outcomes
At the end of this chapter you will be able to:
• Use Python interactively. • Create files containing Python
• Evaluate arithmetic expressions programs and execute them.
using Python. • Import modules to be able to make
• Draw some simple pictures using use of facilities from the standard
the Python Turtle module. library.
These days, wherever electricity is available, there are computers. Although the
term computer generally conjures up the idea of a desktop workstation or laptop,
not all computers are that obvious. Almost all car engines now are controlled by
one or more computers. Many household washing machines are controlled by a
computer. From workstations and laptops, the Web, the Internet, televisions, set-
top boxes, games consoles, cameras, washing machines, car engines, all the way
down to smartcards, computers have become an integral and ubiquitous part of
modern day living, at least in the first and second worlds.
Computers are not however complete systems in themselves: a computer by
itself cannot actually do anything, it is just a lump of hardware that has potential.
For a computer to be useful, it has to have programs to tell it what to do. The utility
and usefulness of a computer depends entirely on the programs used: a computer
is the hardware platform on which software directs the behavior of the complete
system.
In the early days of computers (1940s–1950s) there were very few of them, they
were used for academic, government or military purposes only and were pro-
grammed in machine code (the binary instruction language of a computer) or,
if you were lucky, in a symbolic representation of machine code usually termed
assembly language. Programming was hard and very few people did it.
As computers moved into the commercial world and the academics did research
on how to program them (1950s–1970s), programming languages such as Lisp,
Fortran, Cobol, Algol-60, etc., were created and used. The idea that people wrote
programs and needed to understand them easily had taken hold. Time moved on,
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
2 Getting Started
more research was done, and we got programming languages like Pascal, Ada, C,
C++. Inventing new programming languages became something of an industry.
Of the many hundreds of programming languages invented only some became
popular and used. For example, TCL, Perl, Objective Caml, Prolog, Haskell, Java,
Ruby and, of course, Python have gained widespread adoption. There are many
similarities and differences between all these programming languages and the
histories of them and the inter-relationships between them are very interesting.
For the moment, we only want to look at two particular issues (we will address
many of the other issues as we go through the book).
1. When we write programs, we use a textual representation. Computers can-
Executing is what a not understand the programs we write directly, they have to be translated
program does when (the official term is compiled ) into a form the computer can work with. Pro-
you double-click on
gramming languages like C, C++, etc. require programs to be compiled to the
its icon using a
graphical user machine code of the computer on which the program is to be executed. Pro-
interface, or when gramming languages like Java, and, most importantly for this book, Python,
you type a use a virtual machine. A virtual machine is an idealized computer for ex-
command in a
command terminal
ecuting programs. The statements of programs written in virtual-machine-
– we will say more based programming language are compiled into the machine language of
about what the virtual machine, and there is then a mechanism to execute these virtual
‘execute’ means in machine instructions on the real computer when the program is executed.
Section 1.2, (page 3).
You may well be asking yourself: “Why bother with virtual machines when
we have real machines?” The answer has to do with being able to execute
the same program on many different computers. With a language like C++, a
An operating program has to be compiled for each architecture and operating system. With
system is the languages such as Java and Python, a program compiled on one machine
software that makes can be executed on another machine without recompilation. This is not a big
all the hardware
work. Examples of issue for individuals working with a single machine, but it is a huge issue
operating systems for organizations which have many computers, all needing to use the same
are: Linux, programs – using virtual-machine-based languages means they do not have
Mac OS X, Solaris, to ensure that all the computers are the same in order to be able to execute
and Windows.
the program – the virtual machine mechanism does that for them.
2. When does compilation happen from the programmer’s perspective? Pro-
grams in languages like C, C++, and Java must be compiled before they
can be executed: an explicitly two stage process, compile then execute. Pro-
grams in languages like Ruby and Python can be executed directly without
any prior explicit compilation step, as translation of the program occurs as
needed behind the scenes.
So what does this mean for us now? ‘Compile as needed’ virtual-machine-
based languages like Python involve significantly less hassle when creating and
executing programs. This means Python programs are easier to work with than
C++ or Java programs, particularly when first learning programming. Python is an
(almost) ideal language for learning to program. Moreover, knowing how to pro-
gram in Python is a great springboard for learning other programming languages
like Ruby, Java and C++, so learning Python first really is a win–win situation.
A Note on Terminology
Programmers often talk about the source code, or sometimes just code, of a program.
The terms source code and code really just mean all the statements that comprise the
program in the language that the programmers are using.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Executing Programs 3
This has the effect, when executed, of writing something to the screen of the
computer. It has affected the world in that it has presented something for the user
to read. Not totally earth shattering but, after all, this is only our first program.
So what has this program shown us? Well, primarily that there are ways of
outputting information for the user to read and there are ways of storing data. The
print statement is the basic output action in Python and the sequence of characters
enclosed in double quotes (i.e. "Hello.") is called a string literal or more usually just
a string. A literal is a value represented directly in the programming language –
the value to be used is literally what we typed in.
A competitor for the simplest Python program is:
print 1
which, when executed, outputs 1. In this program we have the integer literal 1
representing the integer value one. Comparing these two programs we see that
the print statement is actually being quite clever: it works out for itself how to deal
with the literal in order to print sensible things to the output.
The question on your lips is, of course: “How is the program executed?” The
most immediate way of executing Python programs is to use the Python system
interactively. This means starting the Python system in interactive mode and then
typing the statements of your program at the Python prompt. How you do this
depends on which operating system you are using.
• On Linux, Mac OS X, and Unix-like systems you type the command python
at a command prompt and this starts the Python system in interactive mode.
Of course, this assumes that Python is installed, which it is by default on
almost all distributions of these operating systems. If, however, the com-
mand doesn’t work on your computer, you will need to download and install
Python. This is probably best achieved using the package manager for your
operating system – for example: synaptic, aptitude or apt-get on Ubuntu;
aptitude or apt-get on Debian; yum on Fedora or Red Hat; pkg-get or pkgadd
on Solaris.
1. Use Cygwin, which includes Python. This works very much like the
Linux and Mac OS X versions of Python – mostly because it is the same
as those versions!
2. Use the Python for Windows system. Installing this (from http://www.
python.org) adds a menu entry in the start menu that has two alternate
ways of running Python in interactive mode:
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
4 Getting Started
The >>> is the interactive Python prompt. We typed the statement, pressed the
return key and the statement was executed immediately. Note that the double
quotes didn’t get output. The double quotes in the program tell the Python system
what the string is, they are not part of the string.
Things should look (more or less) the same whichever of the interactive versions
of Python you try and certainly programs will behave the same on any Python sys-
tem. This is a crucial point: Python looks and behaves the same on all computers.
This sameness on all computers is one of the many benefits of using a system based
on a virtual machine. Programmers can create programs in the full knowledge that
the virtual machine takes care of all the differences between the actual computers
being used. So we have portability of programs between different computers,
exactly what we, as programmers, want.
Figure 1.1
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
And If Something Goes Wrong? 5
WORA Concept
Sun Microsystems use the (trademarked) phrase ‘write once, run anywhere’ about Java.
The concept behind the phrase is as applicable to Python as it is to Java, perhaps more
so.
The two programs seen so far, being relatively simple (!), have no errors in them.
Being error-free is an unusual situation for a program, but more on this later. What
happens if there had been an error? The Python system would have told us so.
For example, if we misspell print as prin then:
>>> prin 1
File "<stdin>", line 1
prin 1
^
SyntaxError: invalid syntax
>>>
“What is syntax?”
and
Syntax is the way in which a statement in a language (any language, not just
programming languages) is constructed.
Natural languages – languages with which humans communicate, for example
English, Mandarin, Cantonese, Spanish – have syntactic rules and most speakers
obey the rules. This is generally so that listeners, who assume the rules are being
obeyed, can easily follow what is being said. Humans are, though, extremely
good at dealing with syntactic errors in the use of language: humans use context,
implicit knowledge, world knowledge and intelligence to construct a meaningful
statement even in the face quite dramatic errors of syntax. It take concentra-
tion and effort, but it is done and often the meaning inferred (or guessed) is the
meaning intended! Sometimes the wrong meaning is inferred and this can be
the basis of much humor or the start of real, all to often violent, conflict. More
usually though, visitors to a community, using a language they are not used to,
can make truly awful errors in the use of the local language and yet still be able to
communicate. People are good at language.
Programming languages are much, much simpler than natural languages and
yet programming language compilers are usually extreme in their complete in-
ability to deal with even the slightest divergence from the expected and allowed
sequence of symbols. This is a very important point to bear in mind when pro- A nice quote,
usually attributed to
graming in order to stay peaceful and sane. You have to remember that compilers Richard Bornat, is:
are literal and, well, fundamentally stupid. Computers aren’t
So, back to the program error. Why are we getting a syntax error in the state- stupid like an ant is
ment: stupid, computers
are stupid like a
prin 1 brick is stupid.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
6 Getting Started
Humans who know a bit about Python will immediately say “Well print is spelt
wrongly.” However, the compiler sees the word prin but does not understand
that it is a misspelling of print, so does not understand the word as print but as
something else. It is only after the space when it sees the 1 that it realizes that
what it is being asked to compile does not correspond with the allowed syntax of
a Python statement. So it is only at the point of reading the 1 that the compiler
appreciates that there is a syntax error. Compilers cannot perform any form of
correction, so you get an error message and must correct the program and execute
it again. This can be frustrating, but remember compilers are literal, they do not
think like humans do. Actually they don’t think at all!
There are two morals to this:
1. Whenever you get a syntax error, always look before as well as at the point
marked to discover and understand what is wrong – it will eventually be-
come second nature. As you get used to decoding error messages do remem-
ber that although the initial cause of the error may actually be your fault,
the compiler is being very unhelpful by not deducing more about what you
meant and giving sensible feedback.
2. Be patient in the face of error messages. At the risk of appearing a bit repeti-
tive: remember, compilers are very literal and you have to do their thinking
for them. Compilers are not like people when it comes to dealing with lan-
guage syntax. More’s the pity.
Memory
Memory in a computer is where everything gets stored during execution. It is usually
measured in bytes. In the mid-1970s computers were lucky to have 16 KB of memory
(16,000 bytes). In mid-2007 computers normally got delivered with at least 1 GB of
memory (1,000,000,000 bytes).
Many people think of computers as just very complicated calculators, and in some
sense this is true. Certainly computers know how to do their sums. For example:
>>> print 4 + 9
13
Programming
languages use *
>>> print 4 - 9
rather than × for -5
multiplication as * is >>> print 4 * 9
on the keyboard 36
and × is not. >>> print 4 / 9
0
>>>
Hmmm. . . that last one seems a bit wrong. The first three are as expected, but that
last one. . . definitely not expected. Having said that, Python cannot have anything
so basic wrong. Perhaps then the Python view of what the expression 4 / 9 means
is different from what we initially assume it means? This is exactly right. When
humans able to do sums see this expression, they know that the result is a fraction:
4
= 0.444̇
9
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Python can Calculate 7
where the dot over the last digit means that that digit recurs forever. So why does
Python do something different?
For various historical reasons, computers do not treat numbers quite as humans
and mathematics do. For most (but not all) computers, 4 is not the same as 4.0:
4 is an integer, whereas 4.0 is a floating point number – floating point numbers
People sometimes
are numbers with both an integer part and a fractional part, and are usually called use the term
floats or sometimes reals. In mathematics, any integer number is a real number, so decimal number
4 and 4.0 are the same value. For computers, though, integers and floats are funda- instead of floating
mentally different: integers and floats are represented differently in the hardware. point number, but
this is not entirely
So as an expression in Python, 4 / 9 says divide the integer 4 by the integer 9 and useful in computing
return an integer result. Since the actual result is a float with only a zero in front as decimal numbers
of the point, the integer result is 0. can be either integer
If instead of 4 / 9 we type 4.0 / 9.0 then we are asking Python to calculate the or floating point!
result of dividing the floating point number 4.0 by the floating point number 9.0,
giving a floating point result:
>>> print 4.0 / 9.0
0.444444444444
This is much more like it. Well, except that there is no indication that the fraction
is a recurring one. This is a consequence of computers having finite amounts of
memory. Since computer floating point numbers must be finite, infinite numbers
cannot be represented in the computer. This means that computer floating point
numbers are not exact but are just approximations to the actual values. For now
we gloss over this, but we will have to return to the issue when we start doing
some serious numerical computations.
Before moving on, we should try creating some more complex expressions to
see whether anything else unexpected happens, or whether our understanding of
evaluating arithmetic expressions from our mathematics education is reflected in
Python. So:
>>> print 2 + 3 * 4
14
>>> print ( 2 + 3 ) * 4
20
>>> print 2 + 3 + 4
9
>>> print 2 + ( 3 + 4 )
9
This seems to indicate that the operations + and * behave as we expect them to: the
precedence (aka priority) of the operations + and * are as we expect from mathe-
matics. Also, parentheses, ( and ), seem to raise the precedence of the operation,
again as we expect from mathematics.
The previous expressions used only integers: what about using floating point
numbers?
>>> print 2.0 + 3.0 * 4.0
14.0
>>> print ( 2.0 + 3.0 ) * 4.0
20.0
>>> print 2.0 + 3.0 + 4.0
9.0
>>> print 2.0 + ( 3.0 + 4.0 )
9.0
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
8 Getting Started
BODMAS
BODMAS is an acronym used by many people to describe the precedence rule of arithmetic. It
stands for:
Brackets
Orders Some people use the acronym
BIDMAS – Indexes replacing
Division and Multiplication Orders.
Addition and Subtraction
The idea behind this acronym is to help you remember that when evaluating an expression, you
first evaluate things in parentheses (brackets) then things raised to powers (exponentiation or
orders) then multiplication and division in left-to-right order, and finally addition and subtraction
in left to right order.
So the same holds true for floating point and integer numbers. We can do further
experiments but if we do we will find all the results to be very much as expected.
If you are not yet convinced yourself, try some really complicated expressions and
It is not actually
impossible to get
see if you can get Python to do the wrong thing. We are confident it will be very
incorrect answers hard!
but you have to Python can be very useful as a calculator, but there is clearly more to Python
work with very than that. Computers often, and workstations and laptops always, have screens
large numbers to
get errors. for displaying things, so let’s investigate drawing pictures on the screen.
Computer numbers
are of finite size so
there are numbers 1.5 Turtles can Draw
that cannot be
stored.
1.5.1 Libraries and Modules
One of the things that makes any programming language powerful is the amount
of pre-written software that comes with it. Python has an extensive library of
software that can be used by any programmer, at any time. This means that you
don’t have to write every program from scratch, you can make use of things in the
library to do as much as possible. This is what makes Python so powerful.
One example is databases. The Python library comes with considerable support
for creating and manipulating databases. This means that if we need to write a
program to manage a database we don’t have to write everything: we can make
use of the library to do much of the hard work for us.
Another example is the support Python offers for user interface graphics which
makes building user interfaces relatively straightforward. Actually, the real com-
plexity of user interfaces is in the design and usability of the interface rather than in
its construction. Python cannot help with those issues: they are human–computer
interaction (HCI) issues.
In fact, the Python library has support for a huge range of software applica-
tions, helping you in almost any programming situation: communicating over the
Internet, creating webpages, drawing pictures, in fact most things you can think
of.
Rather than having the whole of the library available all the time, the library is
structured as a set of modules. Each module is self-contained and so can be used
independently of other modules. This means that we can tell the Python system
to use just the parts needed for a particular program. The import statement is the
way we tell the Python system that we need to make use of a module.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Turtles can Draw 9
Now we can do something with the Turtle module. First let’s try the standard
demonstration to get the turtle to show us what it can do. We do this by typing
turtle.demo ( ) after the import statement:
>>> import turtle
>>> turtle.demo ( )
Figure 1.2 shows the result of executing the statements. As is clear from the figure,
the turtle can draw lines of different thickness, create shapes, fill those shapes and
write text. What is not so obvious from the figure (given that it is monochrome) is
Figure 1.2
Result of running
the demo function
in the Turtle
module. Some of
this is colored red.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
10 Getting Started
that various parts of the image are in different colors. If you run the demonstration
yourself, you will see all the colors involved.
The statement we entered to run the turtle demo is clearly different from the
print and import statements. Firstly, we used the name turtle.demo, i.e. we gave
the name of the module followed by a period (aka full stop) then the name of
the action. Secondly, we appended an open and close parenthesis, i.e. we typed
turtle.demo ( ) rather than turtle.demo. turtle.demo is an example of a function and
we append the parentheses to indicate that the function should be executed. If we
had not put the parentheses, we get:
>>> turtle.demo
<function demo at 0xb7ac72cc>
>>>
which tells us that turtle.demo is a function that resides at some location in the
memory of the computer.
“What is a function?” you are asking. A function is a way of collecting together
a sequence of statements and giving it a name, so that the sequence of statements
can be executed without having to type them all out. Indeed we don’t even have
to know what the sequence of statements is to be able to execute it, we just have to
know what the name is – as with the turtle.demo function above.
Modules can have many functions: the Turtle module has many for drawing
different shapes.
Figure 1.3
Result of calling
turtle.reset.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Turtles can Draw 11
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
Measuring Angles
Angles can be measured in radians but most people learn about degrees and not
radians, so the Turtle module works with degrees by default. We can work with radians
if we want, we just have to call turtle.radians.
As you might already have guessed, the Turtle module also provides functions
for moving backwards (turtle.backward) and turning clockwise (turtle.right), along
with many other drawing functions.
Figure 1.4
Drawing a
square.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
12 Getting Started
call to the turtle.color function, so we need to draw something new to see that the
change of color has happened:
>>> turtle.reset ( )
>>> turtle.color ( "Red" )
>>> turtle.forward ( 10 )
Figure 1.5
Drawing in a new
color. As the book
is monochrome
the line looks
grey, but if you
try this for
yourself, you will
see it is red.
Figure 1.6
Drawing a
dashed line.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Turtles can Draw 13
The Turtle module has the turtle.circle function which, unsurprisingly, draws
circles. So, for example, typing:
>>> turtle.reset ( )
>>> turtle.circle ( 50 )
gives the result shown in Figure 1.7. The parameter to the turtle.circle function
specifies the radius (in pixels) of the circle to be drawn. The turtle starts drawing
in the direction it is facing and draws a circle of the specified radius ending in the
position and direction in which it started.
The turtle.circle function can draw circular arcs as well as complete circles: we
can give calls of turtle.circle a second parameter that specifies how much of a circle
to draw. By typing:
>>> turtle.reset ( )
>>> turtle.circle ( 50 , 180 )
we get only a half a circle, as shown in Figure 1.8. When we call the turtle.circle
function with only one parameter, the Python system assumes we are telling it to
draw all 360° of the circle. Calling the function with a second parameter overrides
this assumption and draws only part of the circle; in this example half a circle
(180°). Circles are always drawn by traveling anti-clockwise, i.e. the center of the
circle or circular arc being drawn is always to the turtle’s left of its current position.
Figure 1.7
Drawing a circle.
Figure 1.8
Drawing half a
circle.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
14 Getting Started
Help
If at any time during an interactive session you want to find out what functions are available in a
module, you can enter help mode by executing the help function:
>>> help ( )
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
help>
At this prompt we can type the name of a module, for example ‘turtle’. The output is quite
lengthy so we will not reproduce it here. Give it a try and you will see information about the
module, including what functions are available. Quite a lot of the information presented may
only make sense after you have a little more experience of Python, but there is also information
there that we want, such as the list of functions we can use.
The best way of finding out what each of the functions can do and what can
be achieved by combining them is to experiment – although we probably ought
to use the term ‘play’ here rather than ‘experiment’, since ‘play’ implies far more
strongly that programming the turtle can be fun!
1.6 Algorithms
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Algorithms 15
The Python system is telling us that it doesn’t have anything called turtle to refer
to, so it can’t run the turtle.reset function for us.
More often, though, getting an algorithm wrong does not result in an error
message, just unexpected results. Let’s take the program for drawing a square of
side 100 pixels:
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
and rearrange it slightly so that it is wrong (we swap the order of the last two
statements):
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
>>> turtle.forward ( 100 )
>>> turtle.forward ( 100 )
>>> turtle.left ( 90 )
Figure 1.9 shows the result. Definitely not a square, but there is no error message,
as there is no error as far as the Python system is concerned. The program we
gave the Python system is a perfectly reasonable program and it executed it as
requested. As the intention was to draw a square, the program clearly has one
or more errors, but not ones the computer can detect. There is nothing wrong
with the syntax of the program, it is either that the algorithm is wrong or that the
correct algorithm has not been correctly implemented, so the result is not what was
intended. In this case, our instructions to Python, which were intended to mean
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
16 Getting Started
‘draw a square’, resulted in an unexpected result because the code was wrong –
we had the right algorithm, but wrote the statements in the wrong order. Such an
error is called (obviously) an algorithmic error or (less obviously) a semantic error.
In the case of algorithms such as that for drawing a square, it is usually fairly
obvious where errors are if they occur. It is then easy to correct the program. How-
ever, for anything but the smallest and simplest of algorithms this is not generally
the case. Semantic errors can be hard to find and sometimes even harder to correct.
Always understand
It is extremely important, therefore, to plan your programs carefully and make sure
what the program you know what they ought to do before you write them.
you are writing is Later in the book (Chapter 9) we will introduce a way of programming, Test-
intended to do Driven Development, that really helps avoid semantic errors. However, we need a
before you write it.
little more programming and Python technology before we can introduce that. So
for the moment we just have to be very careful.
Figure 1.9
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Designing an Algorithm: Square Spirals 17
Looking at Figure 1.10, we see that a square spiral is made up of straight lines
joined together at right angles, almost a square but not quite. Looking at the center
of the example and tracing it out, we see that all the joins of this example are left-
hand turns. So, to draw this figure, our program is going to be made up of calls to Have we mentioned
what a good idea it
the turtle.forward and turtle.left functions. As all the joins are right-angles, the turtle is to understand
will always need to turn left by 90° at the end of each straight line. what the program
So what distinguishes a square spiral from a square? Tracing out the square you are writing is
spiral from the center, we see that the straight lines get longer. In this example, we intended to do
before you write it?
draw two lines of the same length, then increase the length of the next pair of lines,
and so on. If we increase the line length too much, the shape will spiral quickly.
If we increase the side length too little then we will spiral out slowly. Of course if
we do not increase the length at all then there is no spiral, we end up drawing a
square over and over again!
So, having thought about how to create the shape we want, we can think about
creating a program. In this case thing are fairly simple: we can trace out the
example and it tells us the algorithm and hence the code to write. Actually, this
is often the easiest way of writing programs like this: draw the shape on a piece
of paper and it tells you what the algorithm is and hence what code is needed to
achieve that shape.
This:
is three sides of a square, with each side the same length. If we trace round this
shape (starting from the lower left-hand corner) we see that, because the third side
is the same length as the other two, the next side to be drawn will meet the first one
and form a square. We don’t want that, so the third side needs to be longer than
the first two, to make a spiral. So, our square spiral algorithm will be something
like this:
Move forward by some amount
Turn left 90°
Move forward by some amount
Turn left 90°
Move forward by a bit more than last time
Turn left 90°
Move forward by new amount
Turn left 90°
Move forward by a bit more than last time
Turn left 90°
Move forward by new amount
...
Figure 1.10
A square spiral.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
18 Getting Started
Figure 1.11
A square spiral
drawn with the
turtle.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Storing and Executing Programs 19
You are probably thinking: “But if I want to draw the shape again, I have to type
it all in again. How tedious.” or even “If I want to compare two slightly different
sequences, I have to type almost the same thing more than once. Irritating.” So,
whilst typing programs in line by line and having each statement executed as soon
as we press the return key is all very instant and can be incredibly useful, it is Always use a text
absolutely clear that we need to be able to prepare our programs before executing editor for editing
them. Obviously, we need to store programs in some way independent of the program code.
Python system that we can then execute as Python programs. In fact, this is the Word processors
such as
usual way of programming: use a text editor to create a file and then get the Python OpenOffice.org and
system to execute that file. So for example we can use a text editor (we use XEmacs Word are not
but any text editor will do) to put the statement: appropriate because
they are intended
print "Hello." for creating
documents not
programs.
into a file, we called our file printHello.py, and then we can then issue the com-
mand python printHello.py to execute the program:
Issuing the Python command without a file name puts the system into interac-
tive mode while giving it a file name causes the system to open the file and execute
the statements in the file. Many people call this script mode to distinguish it from
interactive mode.
The Python system is fundamentally the same whichever mode we use it in.
In particular, any program executed in either way will behave the same and all
errors are the same and reported in the same way. For example, the faulty Python
program:
prin 1
which is exactly (well almost exactly) the same message as we got in interactive
mode – the difference is that the name of the file is given instead of ‘<stdin>’.
As far as the Python system is concerned all input and output happens through
files. The file could be a real file on disk or it could be a ‘special’ file which is
actually connected to a human input device, for example the keyboard. The file
associated with the keyboard is called ‘stdin’, hence the error message from earlier
said the input was from ‘<stdin>’ – the ’<’ and ’>’ are there to show it is a special
file, and not a file on disk. The Python compilation and execution system does not
distinguish the two cases, a file is a file as far as it is concerned. So using the Python
system in either script mode or interactive mode really is the same.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
20 Getting Started
Chapter Summary
In this chapter we have found that:
• Python programs are sequences of statements.
• Python handles arithmetic and arithmetic expressions very much as expected,
except for the issue of integer and floating point numbers.
• Python has a large library, structured as a set of modules.
• Python modules contain functions which we can call to do various things.
• The Python system has an interactive mode and a script mode.
• Python programs are usually constructed using a text editor as files on disk, and
then executed in script mode.
Self-Review Questions
Self-review 1.2 Why is the following the case – rather than the result being 13?
>>> print "4 + 9"
4+9
>>>
Self-review 1.3 Why does the expression 2 + 3 * 4 result in the value 14 and not
the value 24?
Self-review 1.10 The Turtle module provides a function to draw circles. If this
function was not available, what algorithm would you use to
draw a circle?
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Programming Exercises 21
Programming Exercises
Exercise 1.1 Estimate the size of your computer screen by importing the Turtle
module and causing the turtle to move 1 pixel (though you may want
to try 10 pixels!).
Exercise 1.2 Experiment with the ‘square spiral’ program, varying the lengths of
various lines. Which values make spirals and which do not? Which
values make the nicest-looking spiral?
Exercise 1.4 Write a program to draw a red circle, then a yellow circle underneath
it and a green circle underneath that. The result should look some-
thing like:
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
22 Getting Started
Exercise 1.5 Amend your program from the previous question so that the circles
are filled and hence the result looks something like:
Exercise 1.6 Write a program to draw a regular hexagon. The result should look
something like:
Hint: Regular hexagons have six sides, of equal length, which meet at
an internal angle of 120°.
Exercise 1.7 Write a program to draw the first letter of your name.
Challenges
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Challenges 23
Hint: You may want to start by doing some trigonometry to sort out
all the angles and lengths. Pythagoras’ Theorem will almost
certainly come in useful: Pythagoras’ Theorem states that for a
right-angled triangle:
p
hypotenuse = x2 + y2
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.