Chapter 1. Programming as a Way of Thinking

The first goal of this book is to teach you how to program in Python. But learning to program means learning a new way to think, so the second goal of this book is to help you 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 trade-offs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.

We will start with the most basic elements of programming and work our way up. In this chapter, we’ll see how Python represents numbers, letters, and words. And you’ll learn to perform arithmetic operations.

You will also start to learn the vocabulary of programming, including terms like operator, expression, value, and type. This vocabulary is important—you will need it to understand the rest of the book, to communicate with other programmers, and to use and understand virtual assistants.

Arithmetic Functions

In addition to the arithmetic operators, Python provides a few functions that work with numbers. For example, the round function takes a floating-point number and rounds it off to the nearest whole number:

round(42.4)
        
42
        
round(42.6)
        
43
        

The abs function computes the absolute value of a number. For a positive number, the absolute value is the number itself:

abs(42)
        
42
        

For a negative number, the absolute value is positive:

abs(-42)
        
42
        

When we use a function like this, we say we’re calling the function. An expression that calls a function is a function call.

When you call a function, the parentheses are required. If you leave them out, you get an error message:

abs 42
        
  Cell In[18], line 1
    abs 42
        ^
SyntaxError: invalid syntax
        

You can ignore the first line of this message; it doesn’t contain any information we need to understand right now. The second line is the code that contains the error, with a caret (^) beneath it to indicate where the error was discovered.

The last line indicates that this is a syntax error, which means that there is something wrong with the structure of the expression. In this example, the problem is that a function call requires parentheses.

Let’s see what happens if you leave out the parentheses and the value:

abs
        
<function abs(x, /)>
        

A function name all by itself is a legal expression that has a value. When it’s displayed, the value indicates that abs is a function, and it includes some additional information I’ll explain later.

Values and Types

So far we’ve seen three kinds of values:

  • 2 is an integer,

  • 42.0 is a floating-point number, and

  • 'Hello' is a string.

A kind of value is called a type. Every value has a type—or we sometimes say it “belongs to” a type.

Python provides a function called type that tells you the type of any value. The type of an integer is int:

type(2)
        
int
        

The type of a floating-point number is float:

type(42.0)
        
float
        

And the type of a string is str:

type('Hello, World!')
        
str
        

The types int, float, and str can be used as functions. For example, int can take a floating-point number and convert it to an integer (always rounding down):

int(42.9)
        
42
        

And float can convert an integer to a floating-point value:

float(42)
        
42.0
        

Now, here’s something that can be confusing. What do you get if you put a sequence of digits in quotes?

'126'
        
'126'
        

It looks like a number, but it is actually a string:

type('126')
        
str
        

If you try to use it like a number, you might get an error:

'126' / 3
        
TypeError: unsupported operand type(s) for /: 'str' and 'int'
        

This example generates a TypeError, which means that the values in the expression, which are called operands, have the wrong type. The error message indicates that the / operator does not support the types of these values, which are str and int.

If you have a string that contains digits, you can use int to convert it to an integer:

int('126') / 3
        
42.0
        

If you have a string that contains digits and a decimal point, you can use float to convert it to a floating-point number:

float('12.6')
        
12.6
        

When you write a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000. This is a legal expression in Python, but the result is not an integer:

1,000,000
        
(1, 0, 0)
        

Python interprets 1,000,000 as a comma-separated sequence of integers. We’ll learn more about this kind of sequence later.

You can use underscores to make large numbers easier to read:

1_000_000
        
1000000
        

Formal and Natural Languages

Natural languages are the languages people speak, like English, Spanish, and French. They were not designed by people; 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. Similarly, programming languages are formal languages that have been designed to express computations.

Although formal and natural languages have some features in common there are important 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 program has exactly one meaning, regardless of context.

Redundancy

In order to make up for ambiguity and reduce misunderstandings, natural languages use redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.

Literalness

Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say.

Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. 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.

Glossary

arithmetic operator: A symbol, like + and *, that denotes an arithmetic operation like addition or multiplication.

integer: A type that represents whole numbers.

floating-point: A type that represents numbers with fractional parts.

integer division: An operator, //, that divides two numbers and rounds down to an integer.

expression: A combination of variables, values, and operators.

value: An integer, floating-point number, or string—or one of other kinds of values we will see later.

function: A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.

function call: An expression—or part of an expression—that runs a function. It consists of the function name followed by an argument list in parentheses.

syntax error: An error in a program that makes it impossible to parse—and therefore impossible to run.

string: A type that represents sequences of characters.

concatenation: Joining two strings end to end.

type: A category of values. The types we have seen so far are integers (type int), floating-point numbers (type float), and strings (type str).

operand: One of the values on which an operator operates.

natural language: Any of the languages that people speak that evolved naturally.

formal language: Any of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs. All programming languages are formal languages.

bug: An error in a program.

debugging: The process of finding and correcting errors.

Exercises