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.
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 something graphical, like processing an image or playing a video.
The details look different in different languages, but a few basic instructions appear in just about every language:
Get data from the keyboard, a file, the network, or some other device.
Display data on the screen, save it in a file, send it over the network, etc.
Perform basic mathematical operations like addition and multiplication.
Check for certain conditions and run the appropriate code.
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 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.
One of the challenges of getting started with Python is that you might have to install Python and related software on your computer.
To simplify this, we are using a Python system built in to Open edX, and later, Jupyter. You are also welcome to install Python on your own machine, but be sure to install Python 3.
Now you’re ready to get started. From here on, I assume that you know how to start the Python interpreter and run code.
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:
This is an example of a print statement, although it doesn’t actually print anything on paper. It displays a result on the screen. In this case, the result is the words
The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.
The parentheses indicate that print is a function. We’ll get to functions in Chapter 3.
After “Hello, World”, the next step is arithmetic. Python provides operators, which are special symbols that represent computations like addition and multiplication.
The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:
The operator / performs division:
You might wonder why the result is 42.0 instead of 42. I’ll explain in the next section.
Finally, the operator ** performs exponentiation; that is, it raises a number to a power:
In some other languages, ^
is used for exponentiation, but
in Python it is a bitwise operator called XOR. If you are not
familiar with bitwise operators, the result will surprise you:
I won’t cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.
The floor division operator, //
, divides
two numbers and rounds down to an integer. For example, suppose the
run time of a movie is 105 minutes. You might want to know how
long that is in hours. Conventional division
returns a decimal number:
But we don’t normally write hours with decimal points. Floor division returns the integer number of hours, rounding down:
To get the remainder, you could subtract off one hour in minutes:
An alternative is to use the modulus operator, %
, which
divides two numbers and returns the remainder.
The modulus operator is more useful than it seems. 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.
A value is one of the basic things a program works with, like a
letter or a number. Some values we have seen so far are 2,
42.0, and ’Hello, World!’
.
These values belong to different types:
2 is an integer, 42.0 is a floating-point number,
and ’Hello, World!’
is a string,
so-called because the letters it contains are strung together.
If you are not sure what type a value has, the interpreter can tell you:
Here type
is a function.
This particular function is sometimes handy for debugging, but we should never use it in real code. There are better ways of checking how we can use a value. For compound types such as lists and dictionaries, the type
function does not give the full type of an object. The rest you need to work out by looking at the object.
In these results, the word “class” is used in the sense of a category; a type is a category of values.
Not surprisingly, integers belong to the type int, strings belong to str and floating-point numbers belong to float.
What about values like ’2’
and ’42.0’
?
They look like numbers, but they are in quotation marks like
strings.
They’re strings.
(Reminder: we use type
only while debugging, to help ensure we know a little about what type of object we are working with. Never use type
in working code.)
When you enter a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
That’s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers. We’ll learn more about this kind of sequence later.
Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.
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. 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 (Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places).
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 section, like this one, with my suggestions for debugging. I hope they help!
The process of formulating a problem, finding a solution, and expressing it.
A programming language like Python that is designed to be easy for humans to read and write.
A programming language that is designed to be easy for a computer to run; also called “machine language” or “assembly language”.
A property of a program that can run on more than one kind of computer.
A program that reads another program and executes it
Characters displayed by the interpreter to indicate that it is ready to take input from the user.
A set of instructions that specifies a computation.
An instruction that causes the Python interpreter to display a value on the screen.
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
One of the basic units of data, like a number or string, that a program manipulates.
A category of values. The types we have seen so far are integers (type int), floating-point numbers (type float), and strings (type str).
A type that represents whole numbers.
A type that represents numbers with fractional parts.
A type that represents sequences of characters.
An error in a program.
The process of finding and correcting bugs.
An operator, denoted //, that divides two numbers and rounds down (toward negative infinity) to an integer.
An operator, denoted with a percent sign (%), that works on integers and returns the remainder when one number is divided by another.
It is a good idea to read this book in front of a computer so you can try out the examples as you go.
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 when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.
In a print statement, what happens if you leave out one of the parentheses, or both?
If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
In math notation, leading zeros are ok, as in 09. What happens if you try this in Python? What about 011?
What happens if you have two values with no operator between them?
Start the Python interpreter and use it as a calculator.
How many seconds are there in 42 minutes 42 seconds?
How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.
If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?