Chapter 1. Introduction
Only ugly languages become popular. Python is the one exception.
Don Knuth
You’re here. Good. Then let’s begin.
You may already know something about computers and Python, or you may not. If I’m going too slow for you in some section, jump ahead a page or two. You won’t hurt my feelings.
So, here we go.
Mysteries
Let’s begin with two mini-mysteries and their solutions. What do you think the following two lines mean?
(Row 1): (RS) K18,ssk,k1,turn work. (Row 2): (WS) Sl 1 pwise,p5,p2tog,p1,turn.
It looks technical, like some kind of computer program. Actually, it’s a knitting pattern; specifically, a fragment describing how to turn the heel of a sock, \ like the one in Figure 1-1.
This makes as much sense to me as a Sudoku puzzle does to one of my cats, but if you’re a knitter, you probably understand it perfectly.
Let’s try another mysterious text, found on an index card. You’ll figure out its purpose right away, although you might not know its final product:
1/2 c. butter or margarine 1/2 c. cream 2 1/2 c. flour 1 t. salt 1 T. sugar 4 c. riced potatoes (cold) Be sure all ingredients are cold before adding flour. Mix all ingredients. Knead thoroughly. Form into 20 balls. Store cold until the next step. For each ball: Spread flour on cloth. Roll ball into a circle with a grooved rolling pin. Fry on griddle until brown spots appear. Turn over and fry other side.
Even if you don’t cook, you probably recognized that it’s a recipe1: a list of food ingredients followed by directions for preparation. But what does it make? It’s lefse, a Norwegian delicacy that resembles a tortilla (Figure 1-2). Slather on some butter and jam or whatever you like, roll it up, and enjoy.
The knitting pattern and the recipe share some features:
-
A regular vocabulary of words, abbreviations, and symbols. Some might be familiar, others mystifying.
-
Rules about what can be said, and where—syntax.
-
A sequence of operations to be performed in order.
-
Sometimes, a repetition of some operations (a loop), such as the method for frying each piece of lefse.
-
Sometimes, a reference to another sequence of operations (in computer terms, a function). In the recipe, you might need to refer to another recipe for ricing potatoes.
-
Assumed knowledge about the context. The recipe assumes you that know what water is and how to boil it. The knitting pattern assumes that you can knit and purl without stabbing yourself too often.
-
Some data to be used, created, or modified — potatoes and yarn.
-
The tools used to work with the data—pots, mixers, ovens, knitting sticks.
-
An expected result. In our examples, something for your feet and something for your stomach. Just don’t mix them up.
Whatever you call them — idioms, jargon, little languages — you see examples of them everywhere. The lingo saves time for people who know it, while mystifying the rest of us. Try deciphering a newspaper column about bridge if you don’t play the game, or a scientific paper if you’re not a scientist (or even if you are, but in a different field).
Little Python Programs
I used the knitting pattern and recipe to demonstrate that programming isn’t that mysterious. It’s largely a matter of learning the right words and the rules.
Now, it helps greatly if there aren’t too many words and rules, and if you don’t need to learn too many of them at once. Our brains can hold only so much at one time.
Python is:
-
A computer programming language
-
Created in 1991 by the Dutch computer scientist Guido van Rossum
-
Grown and guided by Guido and others since then
-
Well designed
-
Easier to read and write than most alternative languages
-
A core of modern data science and artificial intelligence (AI) computing
-
A valuable skill in today’s computing job market
-
Useful for small scripts, but also huge systems like Instagram.
Let’s finally see a small but real computer program (Example 1-1). What do you think this does?
Example 1-1. countdown.py
for
countdown
in
5
,
4
,
3
,
2
,
1
,
"hey!"
:
(
countdown
)
If you guessed that it’s a Python program that prints the lines
5 4 3 2 1 hey!
then you know that Python can be easier to learn than a recipe or knitting pattern. And you can practice writing Python programs from the comfort and safety of your desk, far from the hazards of hot water and pointy sticks.
The Python program has some special words and symbols
—
for
, in
, print
, commas, colons, parentheses,
and so on
—
that are important parts of the language’s
syntax (rules).
The good news is that Python has a nicer syntax,
and less of it to remember,
than most computer languages.
It seems more natural
—
almost like a recipe.
Example 1-2 is another tiny Python program; it selects one Harry Potter spell from a Python list and prints it.
Example 1-2. spells.py
spells
=
[
"Riddikulus!"
,
"Wingardium Leviosa!"
,
"Avada Kedavra!"
,
"Expecto Patronum!"
,
"Nox!"
,
"Lumos!"
,
]
(
spells
[
3
])
The individual spells are Python strings
(sequences of text characters, enclosed in quotes).
They’re separated by commas and
enclosed in a Python list that’s defined
by enclosing square brackets ([
and ]
).
The word spells
is a variable that gives the list
a name so that we can do things with it.
In this case,
the program would print the fourth spell:
Expecto Patronum!
Why did we say 3
if we wanted the fourth?
A Python list such as spells
is
a sequence of values,
accessed by their offset from
the beginning of the list.
The first value is at offset 0
,
and the fourth value is at offset 3
.
Note
People count from 1, so it might seem weird to count from 0. It helps to think in terms of offsets instead of positions. Yes, this is an example of how computer programs sometimes differ from common language usage.
Lists are very common data structures in Python, and Chapter 8 shows how to use them.
The program in Example 1-3 prints a quote from one of the Three Stooges, but referenced by who said it rather than its position in a list.
Example 1-3. quotes.py
quotes
=
{
"Moe"
:
"A wise guy, huh?"
,
"Larry"
:
"Ow!"
,
"Curly"
:
"Nyuk nyuk!"
,
}
stooge
=
"Curly"
(
stooge
,
"says:"
,
quotes
[
stooge
])
If you were to run this little program, it would print the following:
Curly says: Nyuk nyuk!
quotes
is a variable that names a Python dictionary
—
a collection of unique keys
(in this example, the name of the Stooge)
and associated values
(here, a notable saying of that Stooge).
Using a dictionary, you can store and look up things by name,
which is often a useful alternative to a list.
The spells
example
used square brackets ([
and ]
) to make a Python list,
and the quotes
example
uses curly brackets ({
and }
,
which are no relation to Curly), to make
a Python dictionary.
Also, a colon (:
) is used to associate each
key in the dictionary with its value.
You can read much more about dictionaries in Chapter 9.
That wasn’t too much syntax at once, I hope. In the next few chapters, you’ll encounter more of these little rules, a bit at a time.
Setup
Most likely, you’re working on one of the three most prominent platforms:
-
Microsoft Windows
-
Apple macOS
-
Linux or other UNIX-like system
Programming is a text-heavy process. Modern operating systems highlight graphic user interfaces (GUIs) for most operations, but to write programs, you’ll need two things on your computer:
-
A terminal window for typing commands.
-
A text editor for creating and modifying files.
Chapter 14 will discuss fancier tools like integrated development environments (IDEs) that provide these features and more in one application, but in Part 1 we only need a text-based terminal window and an editor. These are all widely available on thr three main platforms that I mentioned above.
Coming right up, and throughout this book, I’ll include platform-specific notes as needed.
Install Python
Unfortunately, many operating systems do not come with Python, so you may need to install it. Even if your system has it, it may be an old version. I recommend getting the most recent version of Python, from the official website: python.org. Click the Downloads button, then the button for your platform, and follow the directions.
Upgrade Python
In computing, it’s common to number software releases as x.y.z, where x is the major version, y is a minor version within x, and z is a small bug fix or other change within y.
As this book was written,
the most recent major.minor release of Python was version 3.13
.
The major version 3
took about ten years to replace the
previous major version 2
.
The minor versions come out roughly
annually2.
In your terminal window, type
python -V
.
You should see something like this:
$ python -V Python 3.13.0b3
Note
If your Python version is earlier than 3.13, watch in this book for notes that indicate things that may act differently in earlier versions.
Run Python Programs
The program python
can be run in two ways:
-
Interactively — you type a line at a time and see what happens
-
Execute a Python file
Let’s try both.
The Python Interactive Interpreter
Sometimes called the Python shell,
this is what you get if you just type python
(I’ve substituted [version info] below,
because the actual details can be long,
and differ across machines and versions):
$ python Python ... [version info] ... Type "help", "copyright", "credits" or "license" for more information. >>>
Each line that starts with >>>
is a prompt
for you to type a line of valid Python code.
You type Python code after that prompt, and it executes it,
line by line.
This is a quick way to test snippets of Python,
and I’ll use it through this book to illustrate
brief examples.
You can type whatever’s in +bold text+
into the Python interpreter on your machine as you read along.
Let’s try it:
$ python Python ... (version info) ... Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello? World?") Hello? World? >>>
print()
is a built-in Python function
and it writes anything
that you put between the parentheses to your terminal.
In this case, we gave it a text string,
which Python indicates with the enclosing quote ("
)
characters.
Python Files
You save Python code in files with a .py extension.
Run a Python file by typing the command python
,
followed by the Python filename.
Save that single line that you typed in the previous section into a file called hello.py:
print("Hello? World?")
Then, in your terminal window, tell Python to run it:
$ python hello.py Hello? World?
Normally, we just use the interactive interpreter to test little chunks of code, and Python files for anything bigger.
Built-In Python Features
Like that print()
function above,
the Python interpreter has built-in
support for the data and code structures
that you’ll see in the following chapters
of Part One.
The Python Standard Library
When you installed the Python interpreter, you also got Python’s
standard library:
a group of Python files that are officially supported for each release.
These handle many of the tasks that you’ll see in Part Three.
You access these from your program with
the import
statement,
which is fully explained in Chapter 12,
and you can see in in the example code Example 1-4
coming up below.
Third-Party Python Packages
You can install Python code written by anyone, and access it the same as you do the standard library. Part Three includes many examples of these.
A Bigger Example
I once worked for the Internet Archive, which has been saving Internet content for years. Its most well known feature is the Wayback Machine3, which has been archiving web pages for years, and is an invaluable resource to find old copies of websites, even some that are long gone. Example 1-4 below accesses the Wayback Machine and illustrates many of the things that you can do with Python, right out of the box. You’ll learn all the details eventually, as you read through this book. (The line numbers are not part of the code, but were added for the explanation that follows.)
Example 1-4. archive.py
1import
webbrowser
2import
json
3from
urllib.request
import
urlopen
4 5(
"Let's find an old website."
)
6site
=
input
(
"Type a website URL: "
)
7era
=
input
(
"Type a year, month, and day, like 20150613: "
)
+
"0000"
8url
=
f
"http://archive.org/wayback/available?url=
{
site
}
×tamp=
{
era
}
"
9response
=
urlopen
(
url
)
10contents
=
response
.
read
()
11text
=
contents
.
decode
(
"utf-8"
)
12data
=
json
.
loads
(
text
)
13try
:
14old_site
=
data
[
"archived_snapshots"
][
"closest"
][
"url"
]
15(
"Found this copy:"
,
old_site
)
16(
"It should appear in your browser now."
)
17webbrowser
.
open
(
old_site
)
18except
:
19(
"Sorry, no luck finding"
,
site
)
This little Python program did a lot in a few fairly readable lines. You don’t know all these terms yet, but you will within the next few chapters. Here’s what’s going on in each line:
-
Import (make available to this program) all the code from the Python standard library module called
webbrowser
. -
Import all the code from the Python standard library module called
json
. -
Import only the
urlopen
function from the standard library moduleurllib.request
. -
A blank line, because we don’t want to feel crowded.
-
Print some initial text to your display.
-
Print a question about a URL, read what you type, and save it in a program variable called
site
. -
Print another question, this time reading a year, month, and day, and then save it in a variable called
era
. Append the hour and minute for midnight ("0000"
); the Wayback Machine will look earlier and later for the closest date and time the page was last grabbed. -
Construct a string variable called
url
to make the Wayback Machine look up its copy of the site and date that you typed. This uses the f-string format that can embed the values of variables. -
Connect to the web server at that URL and request a particular web service.
-
Get the response data and assign to the variable
contents
. -
Decode
contents
to a text string in JSON format, and assign to the variabletext
. -
Convert
text
todata
—Python data structures. -
Error-checking:
try
to run the next four lines, and if any fail, run the last line of the program (after theexcept
). -
If we got back a match for this site and date, extract its value from a three-level Python dictionary. Notice that this line and the next three are indented. That’s how Python knows that they are part the
try
section. -
Print the URL that we found.
-
Print what will happen after the next line executes.
-
Display the URL we found in your web browser.
-
If anything failed in the previous four lines, Python jumps down to here.
-
If it failed, print a message and the site that we were looking for. This is indented because it should be run only if the preceding
except
line runs.
Note
Most computing languages use some character delimiters
to indicate the start and end of multiline code blocks.
Some use literal words like start
and end
,
and the “curly brace” languages (C, C++, Java,
JavaScript, and many others) use {
and }
.
Python uses consistent indentation instead.
It makes the code a bit less busy and easier to read.
When I ran this in a terminal window, I typed a news site URL and a historic date, and got this text output:
$ python archive.py Let's find an old website. Type a website URL: xkcd.com Type a year, month, and day, like 20150613: 20240728 Found this copy: http://web.archive.org/web/20240727204346/https://xkcd.com/ It should appear in your browser now.
And Figure 1-3 shows what appeared in my browser.
For various reasons, the saved archive pages are sometimes missing content, like images, that had been on the original site. At the top of the archived page above is an added bar that lets you access any past archive of that site. The Archive is a great tool to learn what people actually said and did at particular times.
Review/Preview
This chapter listed the minimal tools that you’ll need to write Python programs, and included a sample program and its output.
Ths next chapter gets into variables and data types, core concepts in any programming language.
Get Introducing Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.