Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
1. Meet Python
Meet Python
Python is a popular, general-purpose programming language created by Guido van Rossum and first released in 1991. It is prized by beginners and professionals alike because its syntax reads almost like plain English. You can use Python to build websites, analyse data, automate boring tasks, control robots, train machine-learning models, and much more. In this chapter you will install Python, learn two ways of running code, and write your very first program.
Why Python?
Three qualities make Python an excellent first language:
- Readable: you write less punctuation and fewer symbols than in many other languages, so you spend more time thinking about ideas and less about syntax.
- Batteries included: Python ships with a large standard library of ready-made tools, so common jobs need very little code.
- Everywhere: it runs on Windows, macOS, and Linux, and a huge community means answers to your questions are easy to find.
Installing Python
Visit python.org and download the latest Python 3 installer for your operating system. On Windows, tick the box that says "Add Python to PATH" before clicking Install. On macOS you can also use the official installer. Once finished, open a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and check the version:
If you see a version number starting with 3, you are ready. (On some systems the command is python3 instead of python.)
The REPL versus a script
There are two common ways to run Python. The first is the REPL (Read-Eval-Print Loop), an interactive prompt where you type one line, press Enter, and immediately see the result. Start it by typing python with no file name. You will see a >>> prompt:
The REPL is perfect for quick experiments. Type exit() to leave it.
The second way is to save your instructions in a script, a plain text file ending in .py. This is how real programs are written, because you can save, edit, and re-run them.
Running a .py file
Create a file called hello.py with one line inside it, then run it from the terminal:
The print() function displays whatever you put between its parentheses. The text in quotation marks is called a string. Printing "Hello, World!" is a tradition for the first program in almost every language.
How a .py file runs
When you type python hello.py, the Python interpreter reads your file line by line, translates it into instructions the computer understands, and runs them. The diagram below shows this journey.
You now have Python installed and have run your first program two different ways. In the next chapters you will learn how to store information, do calculations, and make decisions. Experiment freely: the REPL cannot break your computer, so try typing expressions and see what happens.