Python is a programming language designed to be read. Its code looks close to plain instructions, which is why it is a common first language and why so many teams keep using it long after they have learned others.
What makes Python readable
Compare the smallest program in two languages. Here is 'Hello, cats!' in C++:
#include <iostream>
int main() {
std::cout << "Hello, cats!";
return 0;
}And here it is in Python:
print("Hello, cats!")The C++ version needs an include, a main function, braces, semicolons and a return value before it prints anything, and leaving out one semicolon stops it compiling. Python drops all of that. You save the file and run it with python3 hello.py, with no separate build step.
Indentation is the structure
Most languages mark blocks with curly braces and treat indentation as a courtesy to the reader. In Python, indentation is the syntax. A line ending in a colon opens a block, and every line indented under it belongs to that block. The layout you see is the structure that runs, so a misplaced block looks wrong at a glance. The style guide, PEP 8, sets the convention at four spaces per level.
Types are worked out as the program runs
You don't declare a variable's type. cans = 3 creates a variable holding an integer, and if you later assign a string to it, Python accepts that too. This is dynamic typing. It keeps short programs short, but some mistakes, such as adding a number to a string, only show up when that line runs. On bigger projects, optional type hints (cans: int = 3) and a checker such as mypy catch them before then.
The five basics
The first things a beginner learns are to print words, store data in variables, make decisions, repeat things with loops and write functions. This short program uses all five:
def sell(fish):
print("Sold", fish)
cans = 3
if cans > 0:
for n in range(cans):
sell("tuna")Reading from the top:
def sell(fish):defines a function with one parameter. Its body is the indented line under it.cans = 3stores a value in a variable.if cans > 0:makes a decision. Its block runs only when the condition is true.for n in range(cans):repeats its block once for each number from 0 to 2.sell("tuna")calls the function, which printsSold tuna.
Run it and you get Sold tuna three times. Those five pieces are enough to write scripts that do useful work.
Where Python is used
Python turns up in many kinds of work, and in most of them the reason is a library rather than the language on its own.
- Web apps and APIs: Django comes with user accounts, an admin panel and a database layer built in. Flask starts small and lets you add only what you need. FastAPI is a common choice for JSON APIs.
- Data analysis: pandas loads tables from CSV files, spreadsheets and databases, then filters, groups and totals them. NumPy handles large arrays of numbers.
- AI and machine learning: TensorFlow, PyTorch and scikit-learn are mostly used from Python, so most tutorials and research code are written in it.
- Automation and scripts: renaming files, moving data between systems, checking a website every hour.
- Games: pygame is a popular way to learn game programming, though commercial engines mostly use other languages.
Example: renaming 500 photos
Say a folder holds photos straight off a camera, named IMG_5062.jpg onwards, and you want them called fish-1.jpg, fish-2.jpg and so on. By hand that takes an afternoon. In Python it takes a few lines with pathlib, which ships with the language:
from pathlib import Path
photos = sorted(Path("photos").glob("IMG_*.jpg"))
for n, photo in enumerate(photos, start=1):
new = photo.with_name(f"fish-{n}.jpg")
print(photo.name, "->", new.name)
photo.rename(new)
print(f"Renamed {len(photos)} fish photos.")glob finds every file that matches the pattern, sorted puts them in order so the numbers follow the original names, and enumerate counts from 1 as it goes. Each rename happens on disk straight away, so try a script like this on a copy of the folder first.
In the video, a script like this runs over a folder of 500 photos and prints each new name as it goes:
Example: tuna sales
Analysis often starts with a few numbers and a question. A week of tuna sales fits in a dictionary:
sales = {"Mon": 38, "Tue": 41, "Wed": 35,
"Thu": 52, "Fri": 67}
print("Total:", sum(sales.values()), "cans")
print("Best day:", max(sales, key=sales.get))This prints Total: 233 cans and Best day: Fri. sum adds the values, and max with key=sales.get picks the day with the highest value. When the figures sit in a spreadsheet with thousands of rows, pandas takes over: pd.read_csv("sales.csv") loads the file into a table you can group and total in a line or two.
The library ecosystem
Python's standard library covers a lot before you install anything: files and folders, dates, JSON, CSV, HTTP and regular expressions among them. The Python tutorial calls this its 'batteries included' philosophy.
Beyond it, the Python Package Index (PyPI) hosts hundreds of thousands of third-party packages, and pip installs them:
python3 -m venv .venv
source .venv/bin/activate
pip install pandasThe first two lines create and switch on a virtual environment: a folder holding this project's own packages, so two projects can use different versions of the same library without clashing. The last line downloads pandas and everything it depends on.
So you rarely build the hard parts yourself. Parsing dates, talking to a database and training a model are solved problems, and your code connects the pieces. How pulling in a library differs from building on a framework is covered in Frameworks vs Libraries.
The trade-off: speed
Python is not the fastest language. The standard interpreter, CPython, compiles your code to bytecode and then runs it one instruction at a time, checking types as it goes. A compiled language such as C, Rust or Go turns the program into machine code ahead of time, so the same loop can run many times faster. Compiler vs Interpreter explains the difference.
For most programs this matters less than it sounds. A typical web app or script spends much of its time waiting on a database, a network request or a disk, and a faster language waits just as long.
The heavy libraries also aren't Python underneath. NumPy, pandas and TensorFlow do their number crunching in compiled C, C++ or Fortran, and Python only tells them what to do. A calculation over a million numbers in NumPy is one call into fast code, not a million trips round a Python loop.
Python is a poor fit where every bit of CPU speed counts, as in a game engine, and where another language is native to the platform: JavaScript in the browser, Swift and Kotlin on phones. A common approach is to write the whole program in Python, measure it, and move only the slow part to a faster language.
Common mistakes
- Mixing tabs and spaces: Python 3 refuses inconsistent indentation with a
TabError. Set your editor to insert four spaces when you press Tab. - Installing every package globally: outside a virtual environment, packages pile up in one place, and upgrading one for a new project can break an old one. Make a virtual environment per project.
- Using a list as a default argument: in
def add(item, items=[]), the list is created once, when the function is defined, and every call shares it. Default toNoneand create the list inside the function. - Writing number-crunching loops by hand: a Python loop over a million values is slow, while the same job in NumPy or pandas is a single call.
Why it suits a first language
Python is popular because it is easy to learn and quick to build with. With less syntax in the way, a beginner spends their attention on ideas that carry over to every language: variables, conditions, loops, functions and breaking a problem into steps. And because the libraries reach so far, they can soon build something they care about, such as a script that tidies their files or a chart of their own data. When they pick up a second language later, only the syntax is new. For a wider plan, see How to learn coding.
Key takeaways
- Python is designed to be readable: indentation marks the blocks and there is little boilerplate.
- Print, variables,
if, loops and functions are enough to write useful scripts. - Its reach into web apps, automation, data analysis and AI comes from libraries such as Django, pandas, NumPy and TensorFlow.
- It runs slower than compiled languages, but its heavy libraries do their work in compiled code.
- Give each project its own virtual environment and install packages into it with pip.