Python
How Python works as a research tool, from the interpreter and package ecosystem to setting up an environment and running scripts and notebooks.
What it is
Python is a free, open-source, general-purpose programming language first released by Guido van Rossum in 1991. It is interpreted, meaning you run source code directly without a separate compile step, and its syntax is designed to be readable, so a short script often looks close to pseudocode.
In research, Python answers the question: how do I load, process, analyze and plot my data, or automate a repetitive task, in a way I can repeat and share? It is used for data analysis, simulation, instrument control, image processing, machine learning and automating calculations in almost every field of science and engineering. Its strength comes less from the core language than from a large ecosystem of scientific libraries such as NumPy, SciPy, pandas and Matplotlib.
Fundamentals
The interpreter
The standard implementation, CPython, reads a .py file, translates it into an intermediate form called bytecode, and executes that bytecode line by line in a virtual machine. You can also use the interpreter interactively: type python in a terminal and you get a prompt (the REPL, read–evaluate–print loop) where each line runs immediately.
Python is dynamically typed: a variable does not have a declared type, and x = 3 followed by x = "three" is allowed. Code blocks are defined by indentation rather than braces, so consistent spacing (four spaces by convention) is part of the syntax, not just style. Only Python 3 should be used for new work; Python 2 reached end of life in 2020.
Why scientific Python is fast enough
Plain Python loops are slow compared with compiled languages such as C or Fortran. Scientific libraries avoid this with vectorization: NumPy stores numbers in compact arrays and performs whole-array operations in precompiled code. Writing y = a * x + b, where x is an array of a million values, runs as one fast operation rather than a million interpreted steps.
Packages and environments
A module is a single .py file of reusable code; a package is a collection of modules. You load them with import, for example import numpy as np. Third-party packages are installed with a package manager:
| Tool | Installs from | Typical use |
|---|---|---|
pip + venv |
PyPI, the Python Package Index | Pure Python projects; built into standard Python |
conda |
Conda channels such as conda-forge | Projects needing non-Python libraries (compilers, GPU or geospatial libraries) |
A virtual environment is an isolated folder with its own interpreter link and its own installed packages. Each project gets one, so upgrading a library for one project cannot break another. The list of packages and versions is recorded in a file such as requirements.txt or environment.yml so others can recreate it.
Scripts and notebooks
A script is a text file run from top to bottom. A Jupyter notebook (.ipynb) is a document of cells containing code, results, plots and formatted notes. Cells are executed by a kernel, a running Python process that keeps variables in memory between cells. Notebooks suit exploration and teaching; scripts suit repeatable pipelines and batch jobs.
Basic operation
The workflow below sets up a clean project and runs code in both forms. Commands are typed in a terminal (Terminal on macOS/Linux, PowerShell or Anaconda Prompt on Windows).
- Install Python 3. Use the installer from python.org or a conda distribution such as Miniforge. Check it works with
python --version(on some systemspython3). - Create a project folder and environment. With venv:
python -m venv .venv, then activate it withsource .venv/bin/activate(macOS/Linux) or.venv\Scripts\activate(Windows). With conda:conda create -n myproject python, thenconda activate myproject. Your prompt changes to show the active environment. - Install packages. For example
pip install numpy scipy pandas matplotlib jupyterlab. Record versions withpip freeze > requirements.txtorconda env export > environment.yml. - Choose an editor. VS Code, PyCharm and Spyder all work; point the editor at the interpreter inside your environment so it uses the same packages.
- Write a script. A typical analysis script imports libraries, reads a data file, computes results and saves a figure or table. Place the main steps under
if __name__ == "__main__":so the file can also be imported by other code. - Run it. With the environment active, type
python analysis.py. On a computing cluster, the same command goes inside a job submission script. - Or work in a notebook. Run
jupyter lab; it opens in your browser. Create a notebook, select your environment’s kernel and run cells with Shift+Enter. - Read what comes out. Output appears as printed text, saved files or figures. If something fails, Python prints a traceback: a list of the calls that led to the error, with the actual error type and message on the last line.
Good practice
- Use one environment per project and never install packages into the operating system’s own Python with administrator rights.
- Before trusting a notebook, restart the kernel and run all cells in order; cells run out of sequence can hide errors.
- Keep code under version control (for example Git) and commit the environment file alongside it.
- Prefer whole-array NumPy or pandas operations over explicit loops for large datasets.
- Avoid hard-coded absolute file paths; use paths relative to the project, for example with
pathlib. - Read the last line of a traceback first, then work upward to find the line of your own code involved.
Key terms
- Interpreter — the program that reads and executes Python code.
- Package — a reusable collection of modules installed and loaded with
import. - pip — the standard tool for installing packages from PyPI.
- Virtual environment — an isolated set of an interpreter and packages for one project.
- Vectorization — applying an operation to a whole array at once in compiled code.
- Kernel — the running process that executes a notebook’s cells and holds its variables.
- Traceback — the error report showing where and why a program failed.
Video coming soon
About five minutes on Python: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.1 Languages and Environments
