1. Why program?

Computers are all around us in the 21st century, and promise to become even more ubiquitous as time goes on. They are having an ever increasing impact on our lives, and we are becoming less and less able to even conceive of living without them.

As Dr. Charles Severance says in the beginning of his Python for Everybody course, “It is important that we learn to tell these computers what to do rather than just let them increasingly control our lives.”

Information in the 21st century is now overwhelmingly distributed through the Internet and the World Wide Web. We do research, entertain ourselves, make purchases, interact with our government, and study and learn online.

If we aspire to have democratic participation in the world of today, at least a basic understanding of computer programming, what it is and what it can do, and the workings of the Web are essential for all informed citizens.

That, in a nut shell, is what this book is about. It has two goals: to teach you to think like a computer programmer, so that you can better understand what computers are and what they can and can not do, and to help you apply this understanding in creating web applications.

Learning to think like a computer programmer is a good end in itself, since the processes used in computer programming combine some of the most important features of mathematics, engineering, and natural science. Like mathematicians, computer programmers 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 programmer 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.

So on one level, you will be learning to program, a useful skill in itself. On another level, you will use programming as a means to an end - creating web applications, which can open the door to you to play an active part in building the tools of the information age.

1.1. What is a computer?

A computer is a machine that can perform mathematical calculations and logical operations on information input to it, outputting the processed information. All computers, from the smart phone in your hand to the server in “the cloud” perform the four operations of input, storage, processing, and output. That, in a nutshell, is what computers do.

Information Processing System

What is fascinating to consider is the form that the information input and output from a computer system takes. In the words of the first Koan on bits from the book Blown to Bits, “It’s all just bits.

Whether you are listening to your favorite tune, watching a movie, checking the weather, analyzing scientific data, or writing your term paper for English class, what the computer “sees” in each and every case is a sequence of bits.

1.2. What is a program?

A computer 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 square root of a number, 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:

input

Get data from the keyboard, a file, or some other device.

output

Display data on the screen or send data to a file or other device.

assignment

Set the value of a storage location denoted by a variable name.

math and logic

Perform basic mathematical operations like addition, and multiplication, and logical operations like and, or, and not.

conditional execution

Check for certain conditions and execute the appropriate sequence of statements.

repetition

Perform some action repeatedly, usually with some variation.

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 more or less like these. Thus, we can describe 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 sequences of these basic instructions.

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

1.3. What is debugging?

Programming is a complex process, and because it is done by human beings, it often leads to errors. Programming errors are called bugs and the process of tracking them down and correcting them 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.

1.4. Syntax errors

Syntax refers to the structure of a program and the rules about that structure. For example, in English, “Do you like programming?” is a syntactically correct sentence, while “Like do programming you?” is not. Python can only execute a program if the program is syntactically correct; otherwise, the process fails and returns an error message.

For most speakers of a natural language, a few syntax errors are not a significant problem, so if a someone new to English asked you, “Like do programming you?”, you would probably understand what they meant.

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, though, you will make fewer errors and find them faster.

1.5. Runtime errors

The second type of error is a runtime error, so called because the error does not appear until you run the program. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. Python has built-in features for exception handling, which you will learn about later.

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

1.6. 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 what you wanted it to do. 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.

1.7. 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 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 kernel that contains millions 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 displaying 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.

1.8. Programming languages are formal languages

Natural languages are the languages that 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 more pertinent to our subject:

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=+6$ is not. H2O is a syntactically correct chemical name, but 2Zz 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=+6$ is that $ is not a legal token in mathematics (at least as far as we know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.

The process of converting a sequence of characters into a sequence of tokens is called lexical analysis. Lexical analysis is an important part of what interpreters and compilers do as they convert source code into object code.

The second type of syntax rule pertains to the structure of a statement— that is, the way the tokens are arranged. The statement 3=+6$ is structurally illegal because you can’t place a plus sign immediately after an equal sign. Similarly, molecular formulas have to have subscripts after the element name, not before.

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 old man kicked the bucket”, you understand that man is the subject and kick is the verb, and bucket the direct object. 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 man and a bucket are and what it means to kick, you will understand the general implication of this sentence.

Of course one of the challenges of natural languages is that they are full of idioms. When we say “The old man kicked the bucket”, there is actually no bucket at all and we actually are saying that the old man died. You won’t see this kind of thing in formal languages like Python.

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

ambiguity

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.

redundancy

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.

literalness

Formal languages mean exactly what they say. On the other hand, natural languages are full of idiom and metaphor. If someone says, “The old man kicked the bucket”, there is probably no bucket and nothing was actually kicked.

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:

poetry

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.

prose

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.

computer program

The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.

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. Little things like spelling errors and bad punctuation, which you can get away with in natural languages, can make a big difference in a formal language.

1.9. The Python programming language

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

As you might infer from the name high-level language, 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. Thus, 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.

But 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 today are written in high-level languages. Low-level languages are used only for a few specialized applications requiring exact control of the computer.

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.

Interpret illustration

A compiler reads the program and translates it completely before the program starts running. In this case, 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.

Compile illustration

Many modern languages use both processes. They are first compiled into a lower level language, called byte code, and then interpreted by a program called a virtual machine. Python uses both processes, but because of the way programmers interact with it, it is considered an interpreted language.

1.10. Interacting with Python

There are two ways to use the Python interpreter: shell mode and script mode. In shell mode, you type Python expressions into the Python shell, and the interpreter immediately shows the result:

$ python3
Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 + 2
4
>>>

The >>> is called the Python prompt. The interpreter uses the prompt to indicate that it is ready for instructions. We typed 2 + 2, and the interpreter evaluated our expression, and replied 4, and on the next line it gave a new prompt, indicating that it is ready for more input.

The Python shell is an example of a REPL, or read-evaluate-print-loop.

Alternatively, you can write your program in a text file and use the interpreter to execute the contents of the file. Such a file is called a script, and using Python in this way is called script mode.

We will use shell mode for learning and testing small pieces of Python code. As soon as a program grows beyond a line or two, it will be time to write it to a file and switch to script mode for development.

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

print("Hello, World!")

This is an example of using the print function, which doesn’t actually print anything on paper. It displays a value on the screen. The quotation marks in the program mark the beginning and end of the value; they don’t appear in the result.

Vim and other text editors

Use a text editor to create a file named hello.py with the contents above. By convention, files that contain Python programs have names that end with .py . Following this convention will help your operating system and other programs identify a file as containing python code. Any text editor will work, but if you have setup vim as described in Configuring Debian for Python Web Development, you can just press the <F3> key to run the program from within the editor.

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.

To run your first program from the unix command prompt, navigate to the directory where the program is located and type:

$ python3 hello.py
Hello, World!

Note

In other development environments, the details of executing programs may differ. Also, most programs are more interesting than this one.

The examples in this book use both the Python interpreter and scripts. You will be able to tell which is intended since shell mode examples will always start with the Python prompt.

Working directly in the interpreter is convenient for testing short pieces of code because you get immediate feedback. Think of it as scratch paper used to help you work out problems. Anything longer than a few lines should be put into a script.

1.11. 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 sometimes helpful to add notes to your programs to explain in natural language what the program is doing.

A comment in a computer program is text that is intended only for the human reader - it is completely ignored by the interpreter.

In Python, the # token starts a comment. The rest of the line is ignored. Here is a new version of Hello, World!, called hello2.py.

#---------------------------------------------------
# This demo program shows off how elegant Python is!
# Written by Joe Soap, December 2010.
# Anyone may freely copy or modify this program.
#---------------------------------------------------
    
print("Hello, World!")     # Isn't this easy! 

You’ll also notice that we’ve left a blank line in the program. Blank lines are also ignored by the interpreter, but comments and blank lines can make your programs much easier for humans to parse. Use them liberally!

Another common use of comments is commenting out a part of your program which is not yet ready to include but which you want to leave in your source for inclusion later.

1.12. The print function

We will be using the print function whenever we need to output data from our programs. Little by little, we will learn more about how to control its use.

print is a function. We will studying functions in depth in the functions chapter, but for now we need to learn just enough about them to use print.

Like all functions, the syntax for the print function begins with the name of the function (which in this case is print), followed by an argument list, enclosed in parathensis ( ).

So far we have only seen print called with a single argument, as in print("Hello World!"), which has a single string as an argument. It is Possible to pass print several argments (any number, in fact), seperated by commas.

>>> print("this", "and", "that")
this and that
>>>

Note that:

  1. Several arguments can be passed to the print function, seperated by commas.

  2. A single space is put between each argument in the output.

To print a blank line, just call print() with no arguments.

>>> print()

>>>

1.13. Glossary

algorithm

A general process for solving a category of problems.

bug

An error in a program.

byte code

An intermediate language between source code and object code. Many modern languages first compile source code into byte code and then interpret the byte code with a program called a virtual machine.

comment

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.

commenting out

Putting part of your program source code behind comments so that it temporarily won’t be included when your program runs. The assumption is that you intend to include it later.

compile

To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.

computer

A programmable device that performs mathematical calculations and logical operations.

debugging

The process of finding and removing any of the three kinds of programming errors.

exception

Another name for a runtime error.

executable

Another name for object code that is ready to be executed.

formal language

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.

high-level language

A programming language like Python that is designed to be easy for humans to read and write.

interpret

To execute a program in a high-level language by translating it one line at a time.

low-level language

A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language.

natural language

Any one of the languages that people speak that evolved naturally.

object code

The output of the compiler after it translates the program.

parse

To examine a program and analyze the syntactic structure.

portability

A property of a program that can run on more than one kind of computer.

print function

A function used in a program or script that causes the Python interpreter to display a value on its output device.

problem solving

The process of formulating a problem, finding a solution, and expressing the solution.

program

a sequence of instructions that specifies to a computer actions and computations to be performed.

Python shell

An interactive user interface to the Python interpreter. The user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for processing.

runtime error

An error that does not occur until the program has started to execute but that prevents the program from continuing.

script

A program stored in a file (usually one that will be interpreted).

semantic error

An error in a program that makes it do something other than what the programmer intended.

semantics

The meaning of a program.

shell mode

A style of using Python where we type expressions at the command prompt, and the results are shown immediately. Contrast with script, and see the entry under Python shell.

source code

A program in a high-level language before being compiled.

syntax

The structure of a program.

syntax error

An error in a program that makes it impossible to parse — and therefore impossible to interpret.

token

One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.

lexical analysis

The process of converting a sequence of characters into a sequence of tokens meaningful in the language.

lexeme

A sequence of characters that matches a pattern for a token in the language.

1.14. Exercises