Appendix 1
Just Enough Python

Welcome to Python! These days, Python is the language for machine learning. From the research labs to the biggest AI companies, Python snaked its way everywhere. (See what I did here?)

Python is a great language all around, but it fits ML particularly well—for two reasons. First, it comes with powerful numerical and scientific libraries. Second, Python is powerful, but also easy to approach. Many people in the ML community lack a background in programming, and would be intimidated by a less friendly language.

Don’t get me wrong: Python isn’t a toy language that you can learn in a day. It comes with sophisticated features that take time to learn and master. The examples in this book, however, avoid those features in favor of a small subset of Python. This appendix is a day trip through that mini-Python. Read it, and you’ll know just enough of the language to read and modify the code in this book.

Here is what we’ll talk about:

At the end, I’ll tell you where to look for more in-depth information.

This appendix moves at a much faster pace than the rest of the book. We won’t linger on basic programming concepts that you already know. In most cases, we’ll glance at a few lines of code, see what Python’s syntax looks like, and move forward. Maybe have a browser handy as you read through, in case you want to dig a bit deeper into a specific Python feature.

While you’re at your computer, you might want to type Python statements as you read through. Open a terminal and check that you have Python 3 installed.

 python3 --version

If the python3 command fails, then try the python command, without a version number—but make sure that your version of Python is 3.0 or later. If you don’t have Python, or you have an earlier version, then look for an installation method that works for you and your system. You’ll find a few on the official “Installing Python” page.[41] If you want to go with the flow, you can also do like most people in the machine learning community, and install Python via the Conda package manager.[42]

There are two main ways to run Python code. One is to write a Python program in a file with a py extension, and execute it:

 python3 my_code.py

You can also execute Python code in an interactive Python interpreter. Start it with the python3 command, without a file name. Once the interpreter is running, you can execute Python statements on the fly—like this one:

 print​(​"Hello, Python!"​)

Oh, by the way: it’s always embarrassing when you don’t know how to close an interactive interpreter. In Python, you do that with the exit() command, or by pressing Ctrl-D.