# Think Python/The way of the program

The goal of this book is to teach you to think like a computer
scientist. This way of thinking combines some of the best features of
mathematics, engineering, and natural science. Like mathematicians,
computer scientists use formal languages to denote ideas (specifically
computations). Like engineers, they design things, assembling components
into systems and evaluating tradeoffs among alternatives. Like
scientists, they observe the behavior of complex systems, form
hypotheses, and test predictions.

The single most important skill for a computer scientist is **problem
solving**. Problem solving means the ability to formulate problems,
think creatively about solutions, and express a solution clearly and
accurately. As it turns out, the process of learning to program is an
excellent opportunity to practice problem-solving skills. That's why
this chapter is called, "The way of the program."

On one level, you will be learning to program, a useful skill by itself.
On another level, you will use programming as a means to an end. As we
go along, that end will become clearer.

## The Python programming language

The programming language you will learn is Python. Python is an example
of a **high-level language**; other high-level languages you might have
heard of are C, C++, Perl, and Java.

There are also **low-level languages**, sometimes referred to as
"machine languages" or "assembly languages." Loosely speaking, computers
can only execute programs written in low-level languages. So programs
written in a high-level language have to be processed before they can
run. This extra processing takes some time, which is a small
disadvantage of high-level languages.

The advantages are enormous. First, it is much easier to program in a
high-level language. Programs written in a high-level language take less
time to write, they are shorter and easier to read, and they are more
likely to be correct. Second, high-level languages are **portable**,
meaning that they can run on different kinds of computers with few or no
modifications. Low-level programs can run on only one kind of computer
and have to be rewritten to run on another.

Due to these advantages, almost all programs are written in high-level
languages. Low-level languages are used only for a few specialized
applications.

Two kinds of programs process high-level languages into low-level
languages: **interpreters** and **compilers**. An interpreter reads a
high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately
reading lines and performing computations.

![](Interpreted_Code_Flow_Diagram.svg "Interpreted_Code_Flow_Diagram.svg")

A compiler reads the program and translates it completely before the
program starts running. In this context, the high-level program is
called the **source code**, and the translated program is called the
**object code** or the **executable**. Once a program is compiled, you
can execute it repeatedly without further translation.

![](Compiled_Code_Flow_Diagram.svg "Compiled_Code_Flow_Diagram.svg")

Python is considered an interpreted language because Python programs are
executed by an interpreter. There are two ways to use the interpreter:
**interactive mode** and **script mode**. In interactive mode, you type
Python programs and the interpreter prints the result:

``` python
>>> 1 + 1
2
```

The chevron, `>>>`, is the **prompt** the interpreter uses to indicate
that it is ready. If you type `1 + 1`, and then press the Enter key, the
interpreter replies `2`.

Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a **script**. By
convention, Python scripts have names that end with `.py`.

To execute the script, you have to tell the interpreter the name of the
file. In a UNIX command window, you would type `python dinsdale.py`. In
other development environments, the details of executing scripts are
different. You can find instructions for your environment at the Python
Website `python.org`.

Working in interactive mode is convenient for testing small pieces of
code because you can type and execute them immediately. But for anything
more than a few lines, you should save your code as a script so you can
modify and execute it in the future.

## What is a program?

A **program** is a sequence of instructions that specifies how to
perform a computation. The computation might be something mathematical,
such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching
and replacing text in a document or (strangely enough) compiling a
program.

The details look different in different languages, but a few basic
instructions appear in just about every language:

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**input:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Get data from the keyboard, a file, or some other device.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**output:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Display data on the screen or send data to a file or other device.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**math:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Perform basic mathematical operations like addition and multiplication.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**conditional execution:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Check for certain conditions and execute the appropriate sequence of
statements.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**repetition:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Perform some action repeatedly, usually with some variation.

```{=html}
</DD>
```
```{=html}
</DL>
```
Believe it or not, that\'s pretty much all there is to it. Every program
you\'ve ever used, no matter how complicated, is made up of instructions
that look pretty much like these. So you can think of programming as the
process of breaking a large, complex task into smaller and smaller
subtasks until the subtasks are simple enough to be performed with one
of these basic instructions.

That may be a little vague, but we will come back to this topic when we
talk about **algorithms**.

## What is debugging?

Programming is error-prone. For whimsical reasons, programming errors
are called **bugs** and the process of tracking them down is called
**debugging**.

Three kinds of errors can occur in a program: syntax errors, runtime
errors, and semantic errors. It is useful to distinguish between them in
order to track them down more quickly.

### Syntax errors

Python can only execute a program if the syntax is correct; otherwise,
the interpreter displays an error message. **Syntax** refers to the
structure of a program and the rules about that structure. For example,
parentheses have to come in matching pairs, so `(1 + 2)` is legal, but
`8)` is a **syntax error**.

In English readers can tolerate most syntax errors, which is why we can
read the poetry of E. E. Cummings without spewing error messages. Python
is not so forgiving. If there is a single syntax error anywhere in your
program, Python will display an error message and quit, and you will not
be able to run your program. During the first few weeks of your
programming career, you will probably spend a lot of time tracking down
syntax errors. As you gain experience, you will make fewer errors and
find them faster.

### Runtime errors

The second type of error is a runtime error, so called because the error
does not appear until after the program has started running. These
errors are also called **exceptions** because they usually indicate that
something exceptional (and bad) has happened.

Runtime errors are rare in the simple programs you will see in the first
few chapters, so it might be a while before you encounter one.

### Semantic errors

The third type of error is the **semantic error**. If there is a
semantic error in your program, it will run successfully in the sense
that the computer will not generate any error messages, but it will not
do the right thing. It will do something else. Specifically, it will do
what you told it to do.

The problem is that the program you wrote is not the program you wanted
to write. The meaning of the program (its semantics) is wrong.
Identifying semantic errors can be tricky because it requires you to
work backward by looking at the output of the program and trying to
figure out what it is doing.

### Experimental debugging

One of the most important skills you will acquire is debugging. Although
it can be frustrating, debugging is one of the most intellectually rich,
challenging, and interesting parts of programming.

In some ways, debugging is like detective work. You are confronted with
clues, and you have to infer the processes and events that led to the
results you see.

Debugging is also like an experimental science. Once you have an idea
about what is going wrong, you modify your program and try again. If
your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your
hypothesis was wrong, you have to come up with a new one. As Sherlock
Holmes pointed out, "When you have eliminated the impossible, whatever
remains, however improbable, must be the truth." (A. Conan Doyle, *The
Sign of Four*)

For some people, programming and debugging are the same thing. That is,
programming is the process of gradually debugging a program until it
does what you want. The idea is that you should start with a program
that does *something* and make small modifications, debugging them as
you go, so that you always have a working program.

For example, Linux is an operating system that contains thousands of
lines of code, but it started out as a simple program Linus Torvalds
used to explore the Intel 80386 chip. According to Larry Greenfield,
"One of Linus's earlier projects was a program that would switch between
printing AAAA and BBBB. This later evolved to Linux." (*The Linux Users'
Guide* Beta Version 1).

Later chapters will make more suggestions about debugging and other
programming practices.

## Formal and natural languages

**Natural languages** are the languages people speak, such as English,
Spanish, and French. They were not designed by people (although people
try to impose some order on them); they evolved naturally.

**Formal languages** are languages that are designed by people for
specific applications. For example, the notation that mathematicians use
is a formal language that is particularly good at denoting relationships
among numbers and symbols. Chemists use a formal language to represent
the chemical structure of molecules. And most importantly:

> **Programming languages are formal languages that have been designed
> to express computations.**

Formal languages tend to have strict rules about syntax. For example,
3 + 3 = 6 is a syntactically correct mathematical statement, but 3 + = 3
\$6 is not. *H*~2~*O* is a syntactically correct chemical formula, but
~2~*Zz* is not.

Syntax rules come in two flavors, pertaining to **tokens** and
structure. Tokens are the basic elements of the language, such as words,
numbers, and chemical elements. One of the problems with 3 + = 3 \$6 is
that `$` is not a legal token in mathematics (at least as far as I
know). Similarly, ~2~*Zz* is not legal because there is no element with
the abbreviation *Zz*.

The second type of syntax error pertains to the structure of a
statement; that is, the way the tokens are arranged. The statement 3 + =
3 \$6 is illegal because even though + and = are legal tokens, you
can\'t have one right after the other. Similarly, in a chemical formula
the subscript comes after the element name, not before.

```{=html}
<DIV CLASS="theorem">
```
**Exercise 1**  *Write a well-structured English sentence with invalid
tokens in it. Then write another sentence with all valid tokens but with
invalid structure.*

```{=html}
</DIV>
```
When you read a sentence in English or a statement in a formal language,
you have to figure out what the structure of the sentence is (although
in a natural language you do this subconsciously). This process is
called **parsing**.

For example, when you hear the sentence, "The penny dropped," you
understand that "the penny" is the subject and "dropped" is the
predicate. Once you have parsed a sentence, you can figure out what it
means, or the semantics of the sentence. Assuming that you know what a
penny is and what it means to drop, you will understand the general
implication of this sentence.

Although formal and natural languages have many features in
common---tokens, structure, syntax, and semantics---there are some
differences:

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**ambiguity:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Natural languages are full of ambiguity, which people deal with by using
contextual clues and other information. Formal languages are designed to
be nearly or completely unambiguous, which means that any statement has
exactly one meaning, regardless of context.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**redundancy:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
In order to make up for ambiguity and reduce misunderstandings, natural
languages employ lots of redundancy. As a result, they are often
verbose. Formal languages are less redundant and more concise.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**literalness:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Natural languages are full of idiom and metaphor. If I say, "The penny
dropped," there is probably no penny and nothing dropping.[^1] Formal
languages mean exactly what they say.

```{=html}
</DD>
```
```{=html}
</DL>
```
People who grow up speaking a natural language---everyone---often have a
hard time adjusting to formal languages. In some ways, the difference
between formal and natural language is like the difference between
poetry and prose, but more so:

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**Poetry:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Words are used for their sounds as well as for their meaning, and the
whole poem together creates an effect or emotional response. Ambiguity
is not only common but often deliberate.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Prose:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The literal meaning of words is more important, and the structure
contributes more meaning. Prose is more amenable to analysis than poetry
but still often ambiguous.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Programs:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The meaning of a computer program is unambiguous and literal, and can be
understood entirely by analysis of the tokens and structure.

```{=html}
</DD>
```
```{=html}
</DL>
```
Here are some suggestions for reading programs (and other formal
languages). First, remember that formal languages are much more dense
than natural languages, so it takes longer to read them. Also, the
structure is very important, so it is usually not a good idea to read
from top to bottom, left to right. Instead, learn to parse the program
in your head, identifying the tokens and interpreting the structure.
Finally, the details matter. Small errors in spelling and punctuation,
which you can get away with in natural languages, can make a big
difference in a formal language.

## The first program

Traditionally, the first program you write in a new language is called
"Hello, World!" because all it does is display the words, "Hello,
World!" In Python, it looks like this:

``` python
print 'Hello, World!'
```

This is an example of a **print statement**,[^2] which doesn\'t actually
print anything on paper. It displays a value on the screen. In this
case, the result is the words

``` python
Hello, World!
```

The quotation marks in the program mark the beginning and end of the
text to be displayed; they don\'t appear in the result.

Some people judge the quality of a programming language by the
simplicity of the "Hello, World!" program. By this standard, Python does
about as well as possible.

## Debugging

It is a good idea to read this book in front of a computer so you can
try out the examples as you go. You can run most of the examples in
interactive mode, but if you put the code into a script, it is easier to
try out variations.

Whenever you are experimenting with a new feature, you should try to
make mistakes. For example, in the "Hello, world!" program, what happens
if you leave out one of the quotation marks? What if you leave out both?
What if you spell `print` wrong?

This kind of experiment helps you remember what you read; it also helps
with debugging, because you get to know what the error messages mean. It
is better to make mistakes now and on purpose than later and
accidentally.

Programming, and especially debugging, sometimes brings out strong
emotions. If you are struggling with a difficult bug, you might feel
angry, despondent or embarrassed.

There is evidence that people naturally respond to computers as if they
were people.[^3] When they work well, we think of them as teammates, and
when they are obstinate or rude, we respond to them the same way we
respond to rude, obstinate people.

Preparing for these reactions might help you deal with them. One
approach is to think of the computer as an employee with certain
strengths, like speed and precision, and particular weaknesses, like
lack of empathy and inability to grasp the big picture.

Your job is to be a good manager: find ways to take advantage of the
strengths and mitigate the weaknesses. And find ways to use your
emotions to engage with the problem, without letting your reactions
interfere with your ability to work effectively.

Learning to debug can be frustrating, but it is a valuable skill that is
useful for many activities beyond programming. At the end of each
chapter there is a debugging section, like this one, with my thoughts
about debugging. I hope they help!

## Glossary

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**problem solving:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of formulating a problem, finding a solution, and expressing
the solution.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**high-level language:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming language like Python that is designed to be easy for
humans to read and write.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**low-level language:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming language that is designed to be easy for a computer to
execute; also called "machine language" or "assembly language."

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**portability:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A property of a program that can run on more than one kind of computer.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interpret:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To execute a program in a high-level language by translating it one line
at a time.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**compile:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**source code:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A program in a high-level language before being compiled.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**object code:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The output of the compiler after it translates the program.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**executable:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Another name for object code that is ready to be executed.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**prompt:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Characters displayed by the interpreter to indicate that it is ready to
take input from the user.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**script:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A program stored in a file (usually one that will be interpreted).

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interactive mode:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of using the Python interpreter by typing commands and expressions
at the prompt.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**script mode:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of using the Python interpreter to read and execute statements in
a script.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**program:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A set of instructions that specifies a computation.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**algorithm:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A general process for solving a category of problems.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**bug:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**debugging:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of finding and removing any of the three kinds of
programming errors.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**syntax:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The structure of a program.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**syntax error:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program that makes it impossible to parse (and therefore
impossible to interpret).

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**exception:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error that is detected while the program is running.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**semantics:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The meaning of a program.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**semantic error:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program that makes it do something other than what the
programmer intended.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**natural language:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Any one of the languages that people speak that evolved naturally.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**formal language:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Any one of the languages that people have designed for specific
purposes, such as representing mathematical ideas or computer programs;
all programming languages are formal languages.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**token:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the basic elements of the syntactic structure of a program,
analogous to a word in a natural language.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**parse:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To examine a program and analyze the syntactic structure.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**print statement:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An instruction that causes the Python interpreter to display a value on
the screen.

```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises

### Exercise 2

Use a web browser to go to the Python website, <http://python.org/>.
This page contains information about Python and links to Python-related
pages, and it gives you the ability to search the Python documentation.
For example, if you enter `print` in the search window, the first link
that appears is the documentation of the `print` statement. At this
point, not all of it will make sense to you, but it is good to know
where it is.

### Exercise 3

Start the Python interpreter and type **\'`help()`**\' to start the
online help utility. Or you can type **`help('print')`** to get
information about the **\'`print`**\' statement.If this example doesn\'t
work, you may need to install additional Python documentation or set an
environment variable; the details depend on your operating system and
version of Python.

### Exercise 4

Start the Python interpreter and use it as a calculator. Python\'s
syntax for math operations is almost the same as standard mathematical
notation. For example, the symbols **\'`+`**\', **\'`-`**\' and
**\'`/`**\' denote addition, subtraction and division, as you would
expect. The symbol for multiplication is **\'`*`**\'.If you run a 10
kilometer race in 43 minutes 30 seconds, what is your average time per
mile? What is your average speed in miles per hour? (Hint: there are
1.61 kilometers in a mile).\'\'

## References

```{=html}
<references/>
```

[^1]: This idiom means that someone realized something after a period of
    confusion.

[^2]: In Python 3.0, `print` is a function, not a statement, so the
    syntax is `print(’Hello, World!’)`. We will get to functions soon!

[^3]: See Reeves and Nass, `<I>`{=html}The Media Equation: How People
    Treat Computers, Television, and New Media Like Real People and
    Places`</I>`{=html}.


# Think Python/Variables, expressions and statements

### Values and types

A **value** is one of the basic things a program works with, like a
letter or a number. The values we have seen so far are `1`, `2`, and
`'Hello, World!'`.

These values belong to different **types**: `2` is an integer, and
`'Hello, World!'` is a **string**, so-called because it contains a
"string" of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.

The print statement also works for integers.

``` python
>>> print (4)
4
```

If you are not sure what type a value has, the interpreter can tell you.

``` python
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
```

Not surprisingly, strings belong to the type `str` and integers belong
to the type `int`. Less obviously, numbers with a decimal point belong
to a type called `float`, because these numbers are represented in a
format called **floating-point**.

``` python
>>> type(3.2)
<type 'float'>
```

What about values like `'17'` and `'3.2'`? They look like numbers, but
they are in quotation marks like strings.

``` python
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
```

They\'re strings.

When you type a large integer, you might be tempted to use commas
between groups of three digits, as in `1,000,000`. This is not a legal
integer in Python, but it is legal:

``` python
>>> print 1,000,000
1 0 0
```

Well, that's not what we expected at all! Python interprets `1,000,000`
as a comma-separated sequence of integers, which it prints with spaces
between.

This is the first example we have seen of a semantic error: the code
runs without producing an error message, but it doesn\'t do the "right"
thing.

### Variables

One of the most powerful features of a programming language is the
ability to manipulate **variables**. A variable is a name that refers to
a value.

An **assignment statement** creates new variables and gives them values:

``` python
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
```

This example makes three assignments. The first assigns a string to a
new variable named `message`; the second gives the integer `17` to `n`;
the third assigns the (approximate) value of π to `pi`.

A common way to represent variables on paper is to write the name with
an arrow pointing to the variable's value. This kind of figure is called
a **state diagram** because it shows what state each of the variables is
in (think of it as the variable's state of mind). This diagram shows the
result of the previous example:

  ----------- --------------- ------------------------------------------------
  `message`   $\rightarrow$   `'And now for something completely different'`
  `n`         $\rightarrow$   `17`
  `pi`        $\rightarrow$   `3.1415926535897931`
  ----------- --------------- ------------------------------------------------

To display the value of a variable, you can use a print statement:

``` python
>>> print n
17
>>> print pi
3.14159265359
```

The type of a variable is the type of the value it refers to.

``` python
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
```

#### Exercise 1

If you type an integer with a leading zero, you might get a confusing
error:

``` python
>>> zipcode = 02492
                 ^
SyntaxError: invalid token
```

Other numbers seem to work, but the results are bizarre:

``` python
>>> zipcode = 02132
>>> print zipcode
1114
```

Can you figure out what is going on? Hint: print the values `01`, `010`,
`0100` and `01000`.

### Variable names and keywords

Programmers generally choose names for their variables that are
meaningful---they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters
and numbers, but they have to begin with a letter. It is legal to use
uppercase letters, but it is a good idea to begin variable names with a
lowercase letter (you\'ll see why later).

The underscore character (`_`) can appear in a name. It is often used in
names with multiple words, such as `my_name` or
`airspeed_of_unladen_swallow`.

If you give a variable an illegal name, you get a syntax error:

``` python
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
```

`76trombones` is illegal because it does not begin with a letter.
`more@` is illegal because it contains an illegal character, `@`. But
what\'s wrong with `class`?

It turns out that `class` is one of Python\'s **keywords**. The
interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.

Python has 31 keywords:

  ------------ ----------- ---------- ---------- ---------
  `and`        `del`       `from`     `not`      `while`
  `as`         `elif`      `global`   `or`       `with`
  `assert`     `else`      `if`       `pass`     `yield`
  `break`      `except`    `import`   `print`
  `class`      `exec`      `in`       `raise`
  `continue`   `finally`   `is`       `return`
  `def`        `for`       `lambda`   `try`
  ------------ ----------- ---------- ---------- ---------

You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don\'t know why, see if it is
on this list.

If you write your code in a text editor that understands Python, you may
find that it makes it easy for you to spot such keyword clashes by
displaying keywords in a different color to ordinary variables. This
feature is called *syntax highlighting*, and most programmers find it
indispensable. This book uses syntax highlighting for its example code,
so in the following example:

``` python
ok_variable = 42
yield = 42
```

you can see that `yield` has been recognized as a keyword and not as an
ordinary variable, since it is colored green.

### Statements

A statement is a unit of code that the Python interpreter can execute.
We have seen two kinds of statements: print and assignment.

When you type a statement in interactive mode, the interpreter executes
it and displays the result, if there is one.

A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements
execute.

For example, the script

``` python
print 1
x = 2
print x
```

produces the output

``` python
1
2
```

The assignment statement produces no output.

### Operators and operands

**Operators** are special symbols that represent computations like
addition and multiplication. The values the operator is applied to are
called **operands**.

The operators `+`, `-`, `*`, `/` and `**` perform addition, subtraction,
multiplication, division and exponentiation, as in the following
examples:

``` python
20+32   hour-1   hour*60+minute   minute/60   5**2   (5+9)*(15-7)
```

In some other languages, `^` is used for exponentiation, but in Python
it is a bitwise operator called XOR. I won't cover bitwise operators in
this book, but you can read about them at
`wiki.python.org/moin/BitwiseOperators`.

The division operator might not do what you expect:

``` python
>>> minute = 59
>>> minute/60
0
```

The value of `minute` is 59, and in conventional arithmetic 59 divided
by 60 is 0.98333, not 0. The reason for the discrepancy is that Python
is performing **floor division**.[^1]

When both of the operands are integers, the result is also an integer;
floor division chops off the fraction part, so in this example it rounds
down to zero.

If either of the operands is a floating-point number, Python performs
floating-point division, and the result is a `float`:

``` python
>>> minute/60.0
0.98333333333333328
```

### Expressions

An **expression** is a combination of values, variables, and operators.
A value all by itself is considered an expression, and so is a variable,
so the following are all legal expressions (assuming that the variable
`x` has been assigned a value):

``` python
17
x
x + 17
```

If you type an expression in interactive mode, the interpreter
**evaluates** it and displays the result:

``` python
>>> 1 + 1
2
```

But in a script, an expression all by itself doesn't do anything! This
is a common source of confusion for beginners.

#### Exercise 2

Type the following statements in the Python interpreter to see what they
do:

``` python
5
x = 5
x + 1
```

Now put the same statements into a script and run it. What is the
output? Modify the script by transforming each expression into a print
statement and then run it again.

### Order of operations

When more than one operator appears in an expression, the order of
evaluation depends on the **rules of precedence**. For mathematical
operators, Python follows mathematical convention. The acronym
**PEMDAS** is a useful way to remember the rules:

-   **P**arentheses have the highest precedence and can be used to force
    an expression to evaluate in the order you want. Since expressions
    in parentheses are evaluated first, `2 * (3-1)` is 4, and
    `(1+1)**(5-2)` is 8. You can also use parentheses to make an
    expression easier to read, as in `(minute * 100) / 60`, even if it
    doesn\'t change the result.
-   **E**xponentiation has the next highest precedence, so `2**1+1` is
    3, not 4, and `3*1**3` is 3, not 27.
-   **M**ultiplication and **D**ivision have the same precedence, which
    is higher than **A**ddition and **S**ubtraction, which also have the
    same precedence. So `2*3-1` is 5, not 4, and `6+4/2` is 8, not 5.
-   Operators with the same precedence are evaluated from left to right.
    So in the expression `degrees / 2 * pi`, the division happens first
    and the result is multiplied by `pi`. To divide by 2 π, you can
    reorder the operands or use parentheses.

### String operations

In general, you cannot perform mathematical operations on strings, even
if the strings look like numbers, so the following are illegal:

``` python
'2'-'1'    'eggs'/'easy'    'third'*'a charm'
```

The `+` operator works with strings, but it might not do what you
expect: it performs **concatenation**, which means joining the strings
by linking them end-to-end. For example:

``` python
first = 'throat'
second = 'warbler'
print first + second
```

The output of this program is `throatwarbler`.

The `*` operator also works on strings; it performs repetition. For
example, `’Spam’*3` is `'SpamSpamSpam'`. If one of the operands is a
string, the other has to be an integer.

This use of `+` and `*` makes sense by analogy with addition and
multiplication. Just as `4*3` is equivalent to `4+4+4`, we expect
`'Spam'*3` to be the same as `'Spam'+'Spam'+'Spam'`, and it is. On the
other hand, there is a significant way in which string concatenation and
repetition are different from integer addition and multiplication. Can
you think of a property that addition has that string concatenation does
not?

### Comments

As programs get bigger and more complicated, they get more difficult to
read. Formal languages are dense, and it is often difficult to look at a
piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing. These notes are
called **comments**, and they start with the `#` symbol:

``` python
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
```

In this case, the comment appears on a line by itself. You can also put
comments at the end of a line:

``` python
percentage = (minute * 100) / 60     # percentage of an hour
```

Everything from the `#` to the end of the line is ignored---it has no
effect on the program.

Comments are most useful when they document non-obvious features of the
code. It is reasonable to assume that the reader can figure out *what*
the code does; it is much more useful to explain *why*.

This comment is redundant with the code and useless:

``` python
v = 5     # assign 5 to v
```

This comment contains useful information that is not in the code:

``` python
v = 5     # velocity in meters/second.
```

Good variable names can reduce the need for comments, but long names can
make complex expressions hard to read, so there is a tradeoff.

### Debugging

At this point the syntax error you are most likely to make is an illegal
variable name, like `class` and `yield`, which are keywords, or
`odd~job` and `US$`, which contain illegal characters.

If you put a space in a variable name, Python thinks it is two operands
without an operator:

``` python
>>> bad name = 5
SyntaxError: invalid syntax
```

For syntax errors, the error messages don't help much. The most common
messages are `SyntaxError: invalid syntax` and
`SyntaxError: invalid token`, neither of which is very informative.

The runtime error you are most likely to make is a "use before def;"
that is, trying to use a variable before you have assigned a value. This
can happen if you spell a variable name wrong:

``` python
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
```

Variables names are case sensitive, so `LaTeX` is not the same as
`latex`.

At this point the most likely cause of a semantic error is the order of
operations. For example, to evaluate 1/2 π, you might be tempted to
write

``` python
>>> 1.0 / 2.0 * pi
```

But the division happens first, so you would get π / 2, which is not the
same thing! There is no way for Python to know what you meant to write,
so in this case you don't get an error message; you just get the wrong
answer.

### Glossary

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**value:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the basic units of data, like a number or string, that a program
manipulates.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**type:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A category of values. The types we have seen so far are integers (type
`int`), floating-point numbers (type `float`), and strings (type `str`).

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**integer:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents whole numbers.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**floating-point:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents numbers with fractional parts.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**string:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents sequences of characters.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**variable:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A name that refers to a value.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**statement:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A section of code that represents a command or action. So far, the
statements we have seen are assignments and print statements.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**assignment:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that assigns a value to a variable.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**state diagram:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A graphical representation of a set of variables and the values they
refer to.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**keyword:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A reserved word that is used by the compiler to parse a program; you
cannot use keywords like `if`, `def`, and `while` as variable names.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**operator:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A special symbol that represents a simple computation like addition,
multiplication, or string concatenation.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**operand:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the values on which an operator operates.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**floor division:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The operation that divides two numbers and chops off the fraction part.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**expression:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A combination of variables, operators, and values that represents a
single result value.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**evaluate:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To simplify an expression by performing the operations in order to yield
a single value.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**rules of precedence:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The set of rules governing the order in which expressions involving
multiple operators and operands are evaluated.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**concatenate:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To join two operands end-to-end.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**comment:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Information in a program that is meant for other programmers (or anyone
reading the source code) and has no effect on the execution of the
program.

```{=html}
</DD>
```
```{=html}
</DL>
```
### Exercises

#### Exercise 3

Assume that we execute the following assignment statements:

``` python
width = 17
height = 12.0
delimiter = '.'
```

For each of the following expressions, write the value of the expression
and the type (of the value of the expression).

``` python
width/2
width/2.0
height/3
1 + 2 * 5
delimiter * 5
```

Use the Python interpreter to check your answers.

#### Exercise 4

Practice using the Python interpreter as a calculator:

-   *The volume of a sphere with radius
    **\'`<I>`{=html}r`</I>`{=html}**\' is **\'4/3**\' π
    `<I>`{=html}r`</I>`{=html}*^*3*^\'\'.

What is the volume of a sphere with radius 5? Hint: 392.6 is wrong!\'\'

-   \'\'Suppose the cover price of a book is \$24.95, but bookstores get
    a

40% discount. Shipping costs \$3 for the first copy and 75 cents for
each additional copy. What is the total wholesale cost for 60
copies?\'\'

-   \'\'If I leave my house at 6:52 am and run 1 mile at an easy pace

(8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at
easy pace again, what time do I get home for breakfast?\'\'

### Notes

[^1]: In Python 3.0, the result of this division is a `float`. The new
    operator `//` performs integer division.


# Think Python/Case study: interface design

### TurtleWorld

To accompany this book, I have written a suite of modules called Swampy.
One of these modules is TurtleWorld, which provides a set of functions
for drawing lines by steering turtles around the screen.

You can download Swampy from
`thinkpython.com/swampy`; follow the
instructions there to install Swampy on your system.

Move into the directory that contains `TurtleWorld.py`, create a file
named `polygon.py` and type in the following code:

``` python
from TurtleWorld import *

world = TurtleWorld()
bob = Turtle()
print bob

wait_for_user()
```

The first line is a variation of the `import` statement we saw before;
instead of creating a module object, it imports the functions from the
module directly, so you can access them without using dot notation.

The next lines create a TurtleWorld assigned to `world` and a Turtle
assigned to `bob`. Printing `bob` yields something like:

``` python
<TurtleWorld.Turtle instance at 0xb7bfbf4c>
```

This means that `bob` refers to an **instance** of a Turtle as defined
in module `TurtleWorld`. In this context, \"instance\" means a member of
a set; this Turtle is one of the set of possible Turtles.

`wait_for_user` tells TurtleWorld to wait for the user to do something,
although in this case there\'s not much for the user to do except close
the window.

TurtleWorld provides several turtle-steering functions: `fd` and `bk`
for forward and backward, and `lt` and `rt` for left and right turns.
Also, each Turtle is holding a pen, which is either down or up; if the
pen is down, the Turtle leaves a trail when it moves. The functions `pu`
and `pd` stand for "pen up" and "pen down."

To draw a right angle, add these lines to the program (after creating
`bob` and before calling `wait_for_user`):

``` python
fd(bob, 100)
rt(bob)
fd(bob, 100)
```

The first line tells `bob` to take 100 steps forward. The second line
tells him to turn right.

When you run this program, you should see `bob` move east and then
south, leaving two line segments behind.

Now modify the program to draw a square. Don't turn the page until
you\'ve got it working!

### Simple repetition

Chances are you wrote something like this (leaving out the code that
creates TurtleWorld and waits for the user):

``` python
fd(bob, 100)
lt(bob)

fd(bob, 100)
lt(bob)

fd(bob, 100)
lt(bob)

fd(bob, 100)
```

We can do the same thing more concisely with a `for` statement. Add this
example to `polygon.py` and run it again:

``` python
for i in range(4):
    print 'Hello!'
```

You should see something like this:

``` python
Hello!
Hello!
Hello!
Hello!
```

This is the simplest use of the `for` statement; we will see more later.
But that should be enough to let you rewrite your square-drawing
program. Don't turn the page until you do.

Here is a `for` statement that draws a square:

``` python
for i in range(4):
    fd(bob, 100)
    lt(bob)
```

The syntax of a `for` statement is similar to a function definition. It
has a header that ends with a colon and an indented body. The body can
contain any number of statements.

A `for` statement is sometimes called a **loop** because the flow of
execution runs through the body and then loops back to the top. In this
case, it runs the body four times.

This version is actually a little different from the previous
square-drawing code because it makes another left turn after drawing the
last side of the square. The extra turn takes a little more time, but it
simplifies the code if we do the same thing every time through the loop.
This version also has the effect of leaving the turtle back in the
starting position, facing in the starting direction.

### Exercises

The following is a series of exercises using TurtleWorld. They are meant
to be fun, but they have a point, too. While you are working on them,
think about what the point is.

The following sections have solutions to the exercises, so don't look
until you have finished (or at least tried).

-   Write a function called `square` that takes a parameter

named `t`, which is a turtle. It should use the turtle to draw a square.
Write a function call that passes `bob` as an argument to `square`, and
then run the program again.

-   Add another parameter, named `length`, to `square`.

Modify the body so length of the sides is `length`, and then modify the
function call to provide a second argument. Run the program again. Test
your program with a range of values for `length`.

-   The functions `lt` and `rt` make 90-degree turns by

default, but you can provide a second argument that specifies the number
of degrees. For example, `lt(bob, 45)` turns `bob` 45 degrees to the
left. Make a copy of `square` and change the name to `polygon`. Add
another parameter named `n` and modify the body so it draws an n-sided
regular polygon. Hint: The angles of an n-sided regular polygon are
360.0 / `<I>`{=html}n`</I>`{=html} degrees.

-   Write a function called `circle` that takes a turtle, `t`,

and radius, `r`, as parameters and that draws an approximate circle by
invoking `polygon` with an appropriate length and number of sides. Test
your function with a range of values of `r`.

Hint: figure out the circumference of the circle and make sure that
`length * n = circumference`.

Another hint: if `bob` is too slow for you, you can speed him up by
changing `bob.delay`, which is the time between moves, in seconds.
`bob.delay = 0.01` ought to get him moving.

-   Make a more general version of `circle` called `arc`

that takes an additional parameter `angle`, which determines what
fraction of a circle to draw. `angle` is in units of degrees, so when
`angle=360`, `arc` should draw a complete circle.

### Encapsulation

The first exercise asks you to put your square-drawing code into a
function definition and then call the function, passing the turtle as a
parameter. Here is a solution:

``` python
def square(t):
    for i in range(4):
        fd(t, 100)
        lt(t)

square(bob)
```

The innermost statements, `fd` and `lt` are indented twice to show that
they are inside the `for` loop, which is inside the function definition.
The next line, `square(bob)`, is flush with the left margin, so that is
the end of both the `for` loop and the function definition.

Inside the function, `t` refers to the same turtle `bob` refers to, so
`lt(t)` has the same effect as `lt(bob)`. So why not call the parameter
`bob`? The idea is that `t` can be any turtle, not just `bob`, so you
could create a second turtle and pass it as an argument to `square`:

``` python
ray = Turtle()
square(ray)
```

Wrapping a piece of code up in a function is called **encapsulation**.
One of the benefits of encapsulation is that it attaches a name to the
code, which serves as a kind of documentation. Another advantage is that
if you re-use the code, it is more concise to call a function twice than
to copy and paste the body!

### Generalization

The next step is to add a `length` parameter to `square`. Here is a
solution:

``` python
def square(t, length):
    for i in range(4):
        fd(t, length)
        lt(t)

square(bob, 100)
```

Adding a parameter to a function is called **generalization** because it
makes the function more general: in the previous version, the square is
always the same size; in this version it can be any size.

The next step is also a generalization. Instead of drawing squares,
`polygon` draws regular polygons with any number of sides. Here is a
solution:

``` python
def polygon(t, n, length):
    angle = 360.0 / n
    for i in range(n):
        fd(t, length)
        lt(t, angle)

polygon(bob, 7, 70)
```

This draws a 7-sided polygon with side length 70. If you have more than
a few numeric arguments, it is easy to forget what they are, or what
order they should be in. It is legal, and sometimes helpful, to include
the names of the parameters in the argument list:

``` python
polygon(bob, n=7, length=70)
```

These are called **keyword arguments** because they include the
parameter names as "keywords" (not to be confused with Python keywords
like `while` and `def`).

This syntax makes the program more readable. It is also a reminder about
how arguments and parameters work: when you call a function, the
arguments are assigned to the parameters.

### Interface design

The next step is to write `circle`, which takes a radius, `r`, as a
parameter. Here is a simple solution that uses `polygon` to draw a
50-sided polygon:

``` python
def circle(t, r):
    circumference = 2 * math.pi * r
    n = 50
    length = circumference / n
    polygon(t, n, length)
```

The first line computes the circumference of a circle with radius `r`
using the formula 2 π `<I>`{=html}r`</I>`{=html}. Since we use
`math.pi`, we have to import `math`. By convention, `import` statements
are usually at the beginning of the script.

`n` is the number of line segments in our approximation of a circle, so
`length` is the length of each segment. Thus, `polygon` draws a 50-sides
polygon that approximates a circle with radius `r`.

One limitation of this solution is that `n` is a constant, which means
that for very big circles, the line segments are too long, and for small
circles, we waste time drawing very small segments. One solution would
be to generalize the function by taking `n` as a parameter. This would
give the user (whoever calls `circle`) more control, but the interface
would be less clean.

The **interface** of a function is a summary of how it is used: what are
the parameters? What does the function do? And what is the return value?
An interface is "clean" if it is "as simple as possible, but not
simpler. (Einstein)"

In this example, `r` belongs in the interface because it specifies the
circle to be drawn. `n` is less appropriate because it pertains to the
details of *how* the circle should be rendered.

Rather than clutter up the interface, it is better to choose an
appropriate value of `n` depending on `circumference`:

``` python
def circle(t, r):
    circumference = 2 * math.pi * r
    n = int(circumference / 3) + 1
    length = circumference / n
    polygon(t, n, length)
```

Now the number of segments is (approximately) `circumference/3`, so the
length of each segment is (approximately) 3, which is small enough that
the circles look good, but big enough to be efficient, and appropriate
for any size circle.

### Refactoring

When I wrote `circle`, I was able to re-use `polygon` because a
many-sided polygon is a good approximation of a circle. But `arc` is not
as cooperative; we can't use `polygon` or `circle` to draw an arc.

One alternative is to start with a copy of `polygon` and transform it
into `arc`. The result might look like this:

``` python
def arc(t, r, angle):
    arc_length = r * math.radians(angle)
    n = int(arc_length / 3) + 1
    step_length = arc_length / n
    step_angle = float(angle) / n

    for i in range(n):
        fd(t, step_length)
        lt(t, step_angle)
```

The second half of this function looks like `polygon`, but we can't
re-use `polygon` without changing the interface. We could generalize
`polygon` to take an angle as a third argument, but then `polygon` would
no longer be an appropriate name! Instead, let's call the more general
function `polyline`:

``` python
def polyline(t, n, length, angle):
    for i in range(n):
        fd(t, length)
        lt(t, angle)
```

Now we can rewrite `polygon` and `arc` to use `polyline`:

``` python
def polygon(t, n, length):
    angle = 360.0 / n
    polyline(t, n, length, angle)

def arc(t, r, angle):
    arc_length = r * math.radians(angle)
    n = int(arc_length / 3) + 1
    step_length = arc_length / n
    step_angle = float(angle) / n
    polyline(t, n, step_length, step_angle)
```

Finally, we can rewrite `circle` to use `arc`:

``` python
def circle(t, r):
    arc(t, r, 360)
```

This process---rearranging a program to improve function interfaces and
facilitate code re-use---is called **refactoring**. In this case, we
noticed that there was similar code in `arc` and `polygon`, so we
"factored it out" into `polyline`.

If we had planned ahead, we might have written `polyline` first and
avoided refactoring, but often you don't know enough at the beginning of
a project to design all the interfaces. Once you start coding, you
understand the problem better. Sometimes refactoring is a sign that you
have learned something.

### A development plan

A **development plan** is a process for writing programs. The process we
used in this case study is "encapsulation and generalization." The steps
of this process are:

-   Start by writing a small program with no function definitions.

```{=html}
<!-- -->
```
-   Once you get the program working, encapsulate it in a function

and give it a name.

-   Generalize the function by adding appropriate parameters.

```{=html}
<!-- -->
```
-   Repeat steps 1--3 until you have a set of working functions.

Copy and paste working code to avoid retyping (and re-debugging).

-   Look for opportunities to improve the program by refactoring.

For example, if you have similar code in several places, consider
factoring it into an appropriately general function.

This process has some drawbacks---we will see alternatives later---but
it can be useful if you don't know ahead of time how to divide the
program into functions. This approach lets you design as you go along.

### docstring

A **docstring** is a string at the beginning of a function that explains
the interface ("doc" is short for "documentation"). Here is an example:

``` python
def polyline(t, length, n, angle):
    """Draw n line segments with the given length and
    angle (in degrees) between them.  t is a turtle.
    """
    for i in range(n):
        fd(t, length)
        lt(t, angle)
```

This docstring is a triple-quoted string, also known as a multiline
string because the triple quotes allow the string to span more than one
line.

It is terse, but it contains the essential information someone would
need to use this function. It explains concisely what the function does
(without getting into the details of how it does it). It explains what
effect each parameter has on the behavior of the function and what type
each parameter should be (if it is not obvious).

Writing this kind of documentation is an important part of interface
design. A well-designed interface should be simple to explain; if you
are having a hard time explaining one of your functions, that might be a
sign that the interface could be improved.

### Debugging

An interface is like a contract between a function and a caller. The
caller agrees to provide certain parameters and the function agrees to
do certain work.

For example, `polyline` requires four arguments. The first has to be a
Turtle (or some other object that works with `fd` and `lt`). The second
has to be a number, and it should probably be positive, although it
turns out that the function works even if it isn't. The third argument
should be an integer; `range` complains otherwise (depending on which
version of Python you are running). The fourth has to be a number, which
is understood to be in degrees.

These requirements are called **preconditions** because they are
supposed to be true before the function starts executing. Conversely,
conditions at the end of the function are **postconditions**.
Postconditions include the intended effect of the function (like drawing
line segments) and any side effects (like moving the Turtle or making
other changes in the World).

Preconditions are the responsibility of the caller. If the caller
violates a (properly documented!) precondition and the function doesn't
work correctly, the bug is in the caller, not the function. However, for
purposes of debugging it is often a good idea for functions to check
their preconditions rather than assume they are true. If every function
checks its preconditions before starting, then if something goes wrong,
you will know which function to blame.

### Glossary

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**instance:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A member of a set. The TurtleWorld in this chapter is a member of the
set of TurtleWorlds.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**loop:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A part of a program that can execute repeatedly.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**encapsulation:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of transforming a sequence of statements into a function
definition.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**generalization:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of replacing something unnecessarily specific (like a
number) with something appropriately general (like a variable or
parameter).

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**keyword argument:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An argument that includes the name of the parameter as a "keyword."

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interface:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A description of how to use a function, including the name and
descriptions of the arguments and return value.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**development plan:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A process for writing programs.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**docstring:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A string that appears in a function definition to document the
function's interface.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**precondition:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A requirement that should be satisfied by the caller before a function
starts.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**postcondition:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A requirement that should be satisfied by the function before it ends.

```{=html}
</DD>
```
```{=html}
</DL>
```
### Exercises

**Exercise 1**   *Download the code in this chapter from
**\'`thinkpython.com/code/polygon.py`**\'.*

-   \'\'Write appropriate docstrings for **\'`polygon`**\',
    **\'`arc`**\' and

**\'`circle`**\'.\'\'

-   \'\'Draw a stack diagram that shows the state of the program

while executing **\'`circle(bob, radius)`**\'. You can do the arithmetic
by hand or add **\'`print`**\' statements to the code.\'\'

-   \'\'The version of **\'`arc`**\' in Section **\'4.7**\' is not

very accurate because the linear approximation of the circle is always
outside the true circle. As a result, the turtle ends up a few units
away from the correct destination. My solution shows a way to reduce the
effect of this error. Read the code and see if it makes sense to you. If
you draw a diagram, you might see how it works.\'\'

**Exercise 2**   *Write an appropriately general set of functions that
can draw flowers like this:*

```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book005.png">`{=html}*

```{=html}
</DIV>
```
*You can download a solution from
**\'`thinkpython.com/code/flower.py`**\'.*

**Exercise 3**   *Write an appropriately general set of functions that
can draw shapes like this:*

```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book006.png">`{=html}*

```{=html}
</DIV>
```
*You can download a solution from
**\'`thinkpython.com/code/pie.py`**\'.*

```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4**  ***\'**\'* *The letters of the alphabet can be
constructed from a moderate number of basic elements, like vertical and
horizontal lines and a few curves. Design a font that can be drawn with
a minimal number of basic elements and then write functions that draw
letters of the alphabet.*

*You should write one function for each letter, with
names`draw_a`,`draw_b`, etc., and put your functions in a file named
**\'`letters.py`**\'. You can download a "turtle typewriter" from
**\'`thinkpython.com/code/typewriter.py`**\' to help you test your
code.*

*You can download a solution from
**\'`thinkpython.com/code/letters.py`**\'.*


# Think Python/Conditional and recursion

## Modulus operator

The **modulus operator** works on
integers and yields the remainder when the first operand is divided by
the second. In Python, the modulus operator is a percent sign (`%`). The
syntax is the same as for other operators:

``` python
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
```

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. For example,
you can check whether one number is divisible by another---if `x % y` is
zero, then `x` is divisible by `y`.

Also, you can extract the right-most digit or digits from a number. For
example, `x % 10` yields the right-most digit of `x` (in base 10).
Similarly `x % 100` yields the last two digits.

## Boolean expressions

A **boolean expression** is an expression that is either true or false.
The following examples use the operator `==`, which compares two
operands and produces `True` if they are equal and `False` otherwise:

``` python
>>> 5 == 5
True
>>> 5 == 6
False
```

`True` and `False` are special values that belong to the type `bool`;
they are not strings:

``` python
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
```

The `==` operator is one of the **comparison operators**; the others
are:

``` python
      x != y               # x is not equal to y
      x > y                # x is greater than y
      x < y                # x is less than y
      x >= y               # x is greater than or equal to y
      x <= y               # x is less than or equal to y
```

Although these operations are probably familiar to you, the Python
symbols are different from the mathematical symbols. A common error is
to use a single equal sign (`=`) instead of a double equal sign (`==`).
Remember that `=` is an assignment operator and `==` is a comparison
operator. There is no such thing as `=<` or `=>`.

## Logical operators

There are three **logical operators**: `and`, `or`, and `not`. The
semantics (meaning) of these operators is similar to their meaning in
English. For example, `x > 0 and x < 10` is true only if `x` is greater
than 0 *and* less than 10.

`n%2 == 0 or n%3 == 0` is true if *either* of the conditions is true,
that is, if the number is divisible by 2 *or* 3.

Finally, the `not` operator negates a boolean expression, so
`not (x > y)` is true if `x > y` is false, that is, if `x` is less than
or equal to `y`.

Strictly speaking, the operands of the logical operators should be
boolean expressions, but Python is not very strict. Any nonzero number
is interpreted as "true."

``` python
>>> 17 and True
True
```

This flexibility can be useful, but there are some subtleties to it that
might be confusing. You might want to avoid it (unless you know what you
are doing).

## Conditional execution

In order to write useful programs, we almost always need the ability to
check conditions and change the behavior of the program accordingly.
**Conditional statements** give us this ability. The simplest form is
the `if` statement:

``` python
if x > 0:
    print 'x is positive'
```

The boolean expression after the `if` statement is called the
**condition**. If it is true, then the indented statement gets executed.
If not, nothing happens.

`if` statements have the same structure as function definitions: a
header followed by an indented block. Statements like this are called
**compound statements**.

There is no limit on the number of statements that can appear in the
body, but there has to be at least one. Occasionally, it is useful to
have a body with no statements (usually as a place keeper for code you
haven\'t written yet). In that case, you can use the `pass` statement,
which does nothing.

``` python
if x < 0:
    pass          # need to handle negative values!
```

## Alternative execution

A second form of the `if` statement is **alternative execution**, in
which there are two possibilities and the condition determines which one
gets executed. The syntax looks like this:

``` python
if x % 2 == 0:
    print 'x is even'
else:
    print 'x is odd'
```

If the remainder when `x` is divided by 2 is 0, then we know that `x` is
even, and the program displays a message to that effect. If the
condition is false, the second set of statements is executed. Since the
condition must be true or false, exactly one of the alternatives will be
executed. The alternatives are called **branches**, because they are
branches in the flow of execution.

## Chained conditionals

Sometimes there are more than two possibilities and we need more than
two branches. One way to express a computation like that is a **chained
conditional**:

``` python
if x < y:
    print 'x is less than y'
elif x > y:
    print 'x is greater than y'
else:
    print 'x and y are equal'
```

`elif` is an abbreviation of "else if." Again, exactly one branch will
be executed. There is no limit on the number of `elif` statements. If
there is an `else` clause, it has to be at the end, but there doesn\'t
have to be one.

``` python
if choice == 'a':
    draw_a()
elif choice == 'b':
    draw_b()
elif choice == 'c':
    draw_c()
```

Each condition is checked in order. If the first is false, the next is
checked, and so on. If one of them is true, the corresponding branch
executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.

## Nested conditionals

One conditional can also be nested within another. We could have written
the trichotomy example like this:

``` python
if x == y:
    print 'x and y are equal'
else:
    if x < y:
        print 'x is less than y'
    else:
        print 'x is greater than y'
```

The outer conditional contains two branches. The first branch contains a
simple statement. The second branch contains another `if` statement,
which has two branches of its own. Those two branches are both simple
statements, although they could have been conditional statements as
well.

Although the indentation of the statements makes the structure apparent,
**nested conditionals** become difficult to read very quickly. In
general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the following code using a
single conditional:

``` python
if 0 < x:
    if x < 10:
        print 'x is a positive single-digit number.'
```

The `print` statement is executed only if we make it past both
conditionals, so we can get the same effect with the `and` operator:

``` python
if 0 < x and x < 10:
    print 'x is a positive single-digit number.'
```

## Recursion

It is legal for one function to call another; it is also legal for a
function to call itself. It may not be obvious why that is a good thing,
but it turns out to be one of the most magical things a program can do.
For example, look at the following function:

``` python
def countdown(n):
    if n <= 0:
        print 'Blastoff!'
    else:
        print n
        countdown(n-1)
```

If `n` is 0 or negative, it outputs the word, "Blastoff!" Otherwise, it
outputs `n` and then calls a function named
`countdown`---itself---passing `n-1` as an argument.

What happens if we call this function like this?

``` python
>>> countdown(3)
```

The execution of `countdown` begins with `n=3`, and since `n` is greater
than 0, it outputs the value 3, and then calls itself\...

> The execution of `countdown` begins with `n=2`, and since `n` is
> greater than 0, it outputs the value 2, and then calls itself\...
>
> > The execution of `countdown` begins with `n=1`, and since `n` is
> > greater than 0, it outputs the value 1, and then calls itself\...
> >
> > > The execution of `countdown` begins with `n=0`, and since `n` is
> > > not greater than 0, it outputs the word, "Blastoff!" and then
> > > returns.
> >
> > The `countdown` that got `n=1` returns.
>
> The `countdown` that got `n=2` returns.

The `countdown` that got `n=3` returns.

And then you\'re back in `__main__`. So, the total output looks like
this:

``` python
3
2
1
Blastoff!
```

A function that calls itself is **recursive**; the process is called
**recursion**.

As another example, we can write a function that prints a string `n`
times.

``` python
def print_n(s, n):
    if n <= 0:
        return
    print s
    print_n(s, n-1)
```

If `n <= 0` the `return` statement exits the function. The flow of
execution immediately returns to the caller, and the remaining lines of
the function are not executed.

The rest of the function is similar to `countdown`: if `n` is greater
than 0, it displays `s` and then calls itself to display `s` *n*−1
additional times. So the number of lines of output is `1 + (n - 1)`,
which adds up to `n`.

For simple examples like this, it is probably easier to use a `for`
loop. But we will see examples later that are hard to write with a `for`
loop and easy to write with recursion, so it is good to start early.

## Stack diagrams for recursive functions

In Section 3.10, we used a stack diagram to represent the state of a
program during a function call. The same kind of diagram can help
interpret a recursive function.

Every time a function gets called, Python creates a new function frame,
which contains the function\'s local variables and parameters. For a
recursive function, there might be more than one frame on the stack at
the same time.

This figure shows a stack diagram for `countdown` called with `n = 3`:

```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book007.png">`{=html}

```{=html}
</DIV>
```
As usual, the top of the stack is the frame for `__main__`. It is empty
because we did not create any variables in `__main__` or pass any
arguments to it.

The four `countdown` frames have different values for the parameter `n`.
The bottom of the stack, where `n=0`, is called the **base case**. It
does not make a recursive call, so there are no more frames.

> Draw a stack diagram for `print_n` called with `s = 'Hello'` and
> `n=2`.

> Write a function called `do_n` that takes a function object and a
> number, `n` as arguments, and that calls the given function `n` times.

## Infinite recursion

If a recursion never reaches a base case, it goes on making recursive
calls forever, and the program never terminates. This is known as
**infinite recursion**, and it is generally not a good idea. Here is a
minimal program with an infinite recursion:

``` python
def recurse():
    recurse()
```

In most programming environments, a program with infinite recursion does
not really run forever. Python reports an error message when the maximum
recursion depth is reached:

``` python
  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
                  .
                  .
                  .
  File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded
```

This traceback is a little bigger than the one we saw in the previous
chapter. When the error occurs, there are 1000 `recurse` frames on the
stack!

## Keyboard input

The programs we have written so far are a bit rude in the sense that
they accept no input from the user. They just do the same thing every
time.

Python provides a built-in function called `raw_input` that gets input
from the keyboard.[^1] When this function is called, the program stops
and waits for the user to type something. When the user presses Return
or Enter, the program resumes and `raw_input` returns what the user
typed as a string.

``` python
>>> input = raw_input()
What are you waiting for?
>>> print input
What are you waiting for?
```

Before getting input from the user, it is a good idea to print a prompt
telling the user what to input. `raw_input` can take a prompt as an
argument:

``` python
>>> name = raw_input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
```

The sequence `\n` at the end of the prompt represents a **newline**,
which is a special character that causes a line break. That\'s why the
user\'s input appears below the prompt.

If you expect the user to type an integer, you can try to convert the
return value to `int`:

``` python
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
```

But if the user types something other than a string of digits, you get
an error:

``` python
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()
```

We will see how to handle this kind of error later.

## Debugging

The traceback Python displays when an error occurs contains a lot of
information, but it can be overwhelming, especially when there are many
frames on the stack. The most useful parts are usually:

-   What kind of error it was, and

```{=html}
<!-- -->
```
-   Where it occurred.

Syntax errors are usually easy to find, but there are a few gotchas.
Whitespace errors can be tricky because spaces and tabs are invisible
and we are used to ignoring them.

``` python
>>> x = 5
>>>  y = 6
  File "<stdin>", line 1
    y = 6
    ^
SyntaxError: invalid syntax
```

In this example, the problem is that the second line is indented by one
space. But the error message points to `y`, which is misleading. In
general, error messages indicate where the problem was discovered, but
the actual error might be earlier in the code, sometimes on a previous
line.

The same is true of runtime errors. Suppose you are trying to compute a
signal-to-noise ratio in decibels. The formula is *SNR*~*db*~ = 10
log~10~ (*P*~*signal*~ / *P*~*noise*~). In Python, you might write
something like this:

``` python
import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
```

But when you run it, you get an error message:

``` python
Traceback (most recent call last):
  File "snr.py", line 5, in ?
    decibels = 10 * math.log10(ratio)
OverflowError: math range error
```

The error message indicates line 5, but there is nothing wrong with that
line. To find the real error, it might be useful to print the value of
`ratio`, which turns out to be 0. The problem is in line 4, because
dividing two integers does floor division. The solution is to represent
signal power and noise power with floating-point values.

In general, error messages tell you where the problem was discovered,
but that is often not where it was caused.

## Glossary

```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**modulus operator:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An operator, denoted with a percent sign (`%`), that works on integers
and yields the remainder when one number is divided by another.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**boolean expression:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An expression whose value is either `True` or `False`.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**comparison operator:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the operators that compares its operands: `==`, `!=`, `>`, `<`,
`>=`, and `<=`.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**logical operator:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the operators that combines boolean expressions: `and`, `or`, and
`not`.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**conditional statement:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that controls the flow of execution depending on some
condition.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**condition:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The boolean expression in a conditional statement that determines which
branch is executed.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**compound statement:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that consists of a header and a body. The header ends with a
colon (:). The body is indented relative to the header.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**body:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The sequence of statements within a compound statement.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**branch:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the alternative sequences of statements in a conditional
statement.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**chained conditional:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional statement with a series of alternative branches.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**nested conditional:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional statement that appears in one of the branches of another
conditional statement.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**recursion:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of calling the function that is currently executing.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**base case:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional branch in a recursive function that does not make a
recursive call.

```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**infinite recursion:**

```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that calls itself recursively without ever reaching the base
case. Eventually, an infinite recursion causes a runtime error.

```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises

**Exercise 1**  \'\'\'

*Fermat\'s Last Theorem says that there are no integers***\'a,b,
andc***\' such that*

```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
**\'a**\'^**\'n**\'^* + *b**\'^**\'n**\'^* = *c**\'^**\'n**\'^* *

```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
for any values of ***\'n***\' greater than 2.\'\'

-   *Write a function named`check_fermat`*\'\' that takes four

parameters---**\'`a`**\', **\'`b`**\', **\'`c`**\' and **\'`n`**\'---and
that checks to see if Fermat\'s theorem holds. If ***\'n***\' is greater
than 2 and it turns out to be true that \'\'

```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
***\'a`<SUP>`{=html}n`</SUP>`{=html}**\' + *b***\'`<SUP>`{=html}n`</SUP>`{=html}**\' = *c***\'`<SUP>`{=html}n`</SUP>`{=html}**\' *\'\'

```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
**\' the program should print, "Holy smokes, Fermat was wrong!"
Otherwise the program should print, "No, that doesn't work."**\'

-   \'\'\'\'Write a function that prompts the user to input values

for \'\'***\'`a`*,*`b`*,*`c`*and*`n`*****, converts them to integers,
and uses**\'**`'check_fermat`**`'`**\' to check whether they violate
Fermat\'s theorem.**\'

**Exercise 2**   *If you are given three sticks, you may or may not be
able to arrange them in a triangle. For example, if one of the sticks is
12 inches long and the other two are one inch long, it is clear that you
will not be able to get the short sticks to meet in the middle. For any
three lengths, there is a simple test to see if it is possible to form a
triangle:*

> *"If any of the three lengths is greater than the sum of the other
> two, then you cannot form a triangle. Otherwise, you can.[^2]"*

-   *Write a function named`is_triangle`*\'\' that takes three

integers as arguments, and that prints either "Yes" or "No," depending
on whether you can or cannot form a triangle from sticks with the given
lengths.\'\'

-   \'\'Write a function that prompts the user to input three stick

lengths, converts them to integers, and uses **`is_triangle`** to check
whether sticks with the given lengths can form a triangle.\'\'

The following exercises use TurtleWorld from Chapter 4:

**Exercise 3**   *Read the following function and see if you can figure
out what it does. Then run it (see the examples in Chapter **\'4**\').*

``` python
''def draw(t, length, n):
    if n == 0:
        return
    angle = 50
    fd(t, length*n)
    lt(t, angle)
    draw(t, length, n-1)
    rt(t, 2*angle)
    draw(t, length, n-1)
    lt(t, angle)
    bk(t, length*n)
''
```

```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4**

*The Koch curve is a fractal that looks something like this:*

```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book008.png">`{=html}*

```{=html}
</DIV>
```
*To draw a Koch curve with length***\'x***\', all you have to do is*

-   *Draw a Koch curve with length*\'*\'x*/3\'*\'.*

```{=html}
<!-- -->
```
-   *Turn left 60 degrees.*

```{=html}
<!-- -->
```
-   *Draw a Koch curve with length*\'*\'x*/3\'*\'.*

```{=html}
<!-- -->
```
-   *Turn right 120 degrees.*

```{=html}
<!-- -->
```
-   *Draw a Koch curve with length*\'*\'x*/3\'*\'.*

```{=html}
<!-- -->
```
-   *Turn left 60 degrees.*

```{=html}
<!-- -->
```
-   *Draw a Koch curve with length*\'*\'x*/3\'*\'.*

*The only exception is if***\'xis less than 3. In that case, you can
just draw a straight line with lengthx***\'.*

-   \'\'Write a function called **\'`koch`**\' that takes a turtle and

a length as parameters, and that uses the turtle to draw a Koch curve
with the given length.\'\'

-   \'\'Write a function called **\'`snowflake`**\' that draws three

Koch curves to make the outline of a snowflake.You can see my solution
at **\'`thinkpython.com/code/koch.py`**\'.\'\'

-   \'\'The Koch curve can be generalized in several ways. See

**\'`wikipedia.org/wiki/Koch_snowflake`**\' for examples and implement
your favorite.\'\'

## Notes

[^1]: In Python 3.0, this function is named `input`

[^2]: If the sum of two lengths equals the third, they form what is
    called a "degenerate" triangle.