1. What is Python?
Welcome! If you've never written code before, you're in the right place. This tutorial will teach you Python programming from absolute zero, with every example focused on physics applications.
What is Programming?
Programming is the process of writing instructions that a computer can follow. Think of it like writing a very detailed recipe—except instead of cooking ingredients, you're telling a computer exactly what calculations to perform and what to display.
Computers are incredibly fast but not very smart. They do exactly what you tell them, nothing more, nothing less. This means we need to be very precise in our instructions. A programming language like Python provides the vocabulary and grammar for writing these instructions.
Why Python?
Python is a programming language—a way to give instructions to a computer. Among the many programming languages that exist, Python stands out because:
- It reads like English: Python code is designed to be readable. Unlike some
languages with lots of symbols and brackets, Python uses plain words like
if,for, andprint. You can often guess what code does just by reading it. - It's interpreted: You can run code line by line and see results immediately—perfect for experimenting and learning. There's no long wait between writing code and seeing what it does.
- It's forgiving: Python handles many technical details for you, letting you focus on solving problems rather than fighting with the language.
- It has powerful scientific tools: Libraries like NumPy and Matplotlib let you do complex calculations and create publication-quality graphs with just a few lines of code.
Why Python for Physics?
In physics, you'll need to: analyse experimental data, solve equations numerically, run simulations, and create visualisations. Python excels at all of these. Most physics departments now teach Python as the primary programming language, and it's used in research labs around the world.
Your First Program
Let's write your very first program! Every programmer's journey starts with a simple program that
displays a message—traditionally "Hello, World!" We'll use Python's print() function to
do this.
Understanding the print() Function
A function is a named piece of code that performs a specific task. Think of it like
a machine: you put something in, and it does something with it. The print() function's
job is to display text on the screen.
To use print():
- Write the word
print - Follow it with parentheses
() - Put the message you want to display inside the parentheses, surrounded by quotation marks
" "
Understanding Comments
Notice the lines starting with #? These are called comments. Python
completely ignores any line that starts with #. Comments are notes you write to explain
your code—they're incredibly important for:
- Explaining why you wrote something a certain way
- Helping others (and your future self!) understand your code
- Temporarily disabling code without deleting it
Try This!
Click in the code box above, change the text inside the quotes to say something else, then click
Run again. Try adding a new print() line! You can't break anything—experiment
freely!
How This Tutorial Works
Every code example in this tutorial is interactive. You can:
- Read the explanation before each code block
- Study the code and its comments
- Run it to see what happens
- Modify it and run again to experiment
- Practice with the exercises at the end of each section
The code runs in your browser using real Python—no installation required! Making mistakes is part of learning, so don't be afraid to experiment.
Next: Getting Started2. Getting Started
While this tutorial runs in your browser, for real projects you'll want Python on your computer. Here's how to set up your environment.
Installing Python
For physics and scientific computing, we recommend Anaconda—a Python distribution that includes all the scientific libraries you'll need:
- Go to anaconda.com/download
- Download the installer for your operating system
- Run the installer and follow the prompts
Anaconda includes Python plus NumPy, Matplotlib, SciPy, Pandas, and Jupyter Notebooks—everything you need for physics work.
Choosing a Code Editor
You'll write code in a code editor or IDE (Integrated Development Environment). Popular options include:
- Jupyter Notebook: (included with Anaconda) Great for interactive exploration and combining code with explanations. Perfect for physics labs and research.
- Visual Studio Code: Free, powerful, works for any programming language.
- Spyder: (included with Anaconda) Similar to MATLAB, designed for scientific work.
Understanding the Interpreter
Python is an interpreted language, meaning it executes code line by line. This is different from compiled languages (like C) where you must compile the entire program before running it.
3. Variables and Data Types
In physics, we work with quantities like mass, velocity, and temperature. In Python, we store these values using variables.
What is a Variable?
A variable is like a labelled container where you can store a piece of information. When you create a variable, you're telling Python: "remember this value and give it this name so I can use it later."
Why do we need variables? Consider calculating kinetic energy: KE = ½mv². Without variables, you'd have to type the actual numbers every time. With variables, you can write:
- Store the mass in a variable called
mass - Store the velocity in a variable called
velocity - Calculate
0.5 * mass * velocity**2
If you want to calculate for a different mass, just change the variable's value—you don't have to rewrite the formula!
Creating Variables (Assignment)
You create a variable using the assignment operator =. This is
different from the equals sign in mathematics! In programming:
=means "store the value on the right into the variable on the left"- The variable name goes on the left
- The value you want to store goes on the right
Python reads mass = 70.0 as "create a variable called 'mass' and store the value 70.0 in
it."
Naming Variables
Good variable names make your code readable:
- Use descriptive names:
velocityis better thanv - Names can contain letters, numbers, and underscores:
initial_velocity - Names must start with a letter, not a number
- Python is case-sensitive:
Massandmassare different variables - Avoid using Python keywords like
print,if,for
Data Types: What Kind of Value is This?
Every value in Python has a type that tells Python what kind of data it is and what operations make sense for it. You wouldn't try to divide a person's name by 2, right? Types help Python understand what it can do with each value.
The type() function tells you what type a value is. The main types you'll use in physics
are:
Integers (int) — Whole Numbers
Integers are whole numbers without any decimal point: ... -3, -2, -1, 0, 1, 2, 3 ... Use integers for things you count: number of particles, iterations in a simulation, quantum numbers.
Floats (float) — Decimal Numbers
Floats (short for "floating-point numbers") are numbers with decimal points. This is your workhorse type for physics—nearly every physical quantity (mass, velocity, energy, etc.) is a float. The "floating point" refers to how the computer stores the decimal point position internally.
Scientific notation: For very large or small numbers, use e notation.
Writing 2.998e8 means 2.998 × 10⁸ (299,800,000). Writing 6.626e-34 means
6.626 × 10⁻³⁴.
Strings (str) — Text
Strings represent text—any sequence of characters. You create a string by enclosing
text in quotation marks (either single ' or double " work identically).
Use strings for experiment names, file paths, units, labels, and output messages.
f-strings: A special feature called "formatted strings" or "f-strings" lets you
embed variable values directly into text. Just put an f before the opening quote and
put variable names inside curly braces {}.
Booleans (bool) — True or False
Booleans have only two possible values: True or False
(note the capital letters!). They're named after mathematician George Boole. Booleans are essential
for making decisions in your code—"Should I continue the simulation? Has the projectile hit the
ground?"
You can create booleans directly, or they're produced when you compare values (we'll use this lots in the Conditionals section).
4. Operators
Operators are special symbols that tell Python to perform calculations or comparisons. Just like in mathematics, operators work on values (called operands) to produce a result. You'll use these constantly for physics calculations.
Arithmetic Operators
Arithmetic operators perform mathematical calculations. Here's the complete list:
+Addition: adds two numbers-Subtraction: subtracts the second from the first*Multiplication: multiplies two numbers/Division: divides the first by the second (always returns a float)//Integer division: divides and rounds down to whole number%Modulo: returns the remainder after division**Exponent: raises to a power (e.g.,2**3= 2³ = 8)
Important: Multiplication and Powers
Python uses * for multiplication (not × or ·) and ** for powers (not
^). So x² is written as x**2, not x^2!
Physics Calculations
Let's put operators to work with real physics formulas. Notice how we translate mathematical notation into Python:
- KE = ½mv² becomes
0.5 * mass * velocity**2 - E = mc² becomes
m * c**2 - F = GMm/r² becomes
G * M * m / r**2
Comparison Operators
Comparison operators compare two values and return a boolean (True or
False). These are essential for making decisions in your code.
>Greater than: is the left bigger than the right?<Less than: is the left smaller than the right?>=Greater than or equal<=Less than or equal==Equal to: are they the same? (note: two equals signs!)!=Not equal to: are they different?
Important: = vs ==
A very common mistake! Use = for assignment (storing a value) and
== for comparison (checking if equal). x = 5 stores 5 in x.
x == 5 checks if x equals 5.
Logical Operators
Logical operators let you combine multiple conditions into one. Think of them as the words "and", "or", and "not" in English:
and: Both must be True — Returns True only if both conditions are True. Like saying "I need fuel AND good weather to launch."or: At least one must be True — Returns True if either condition is True. Like saying "I'll eat pizza OR pasta."not: Flips the value — Returns the opposite: True becomes False, False becomes True.
5. Data Structures: Lists, Tuples, and Dictionaries
So far, we've stored single values in variables—one mass, one velocity, one time. But in real physics experiments, you rarely work with just one number. You might have:
- 100 temperature readings taken every second
- Positions of 50 particles in a simulation
- Properties of multiple elements (mass, charge, radius)
Data structures are containers that hold multiple values. Python provides several types, each suited for different situations.
Lists: Ordered, Changeable Collections
A list is the most commonly used data structure in Python. Think of it as a numbered container that can hold many items in a specific order.
- Created with square brackets:
[item1, item2, item3] - Ordered: Items stay in the order you put them
- Mutable: You can add, remove, or change items after creation
- Indexed: Access items by their position number (starting from 0!)
Important: Indexing Starts at 0
In Python, the first item has index 0, the second has index 1, and so on. This is different from some other languages and takes getting used to!
List Operations
Tuples: Ordered, Unchangeable Collections
A tuple is like a list, but immutable—once created, you cannot
change it. Use tuples for data that should never be modified, like physical constants or fixed
coordinates. Tuples use parentheses ().
Dictionaries: Key-Value Pairs
A dictionary stores data as key-value pairs. Instead of accessing items by position, you look them up by their key (like a word in a dictionary). This is perfect for storing properties of objects.
Exercise
Create a dictionary for an electron with properties: name, symbol, mass_kg (9.109e-31), charge_C (-1.6022e-19), and spin (0.5). Print its mass.
6. Conditional Statements
So far, our programs run every line of code from top to bottom. But what if we want our code to make decisions? For example:
- "If the temperature exceeds 373K, water is boiling"
- "If the velocity is negative, the object is moving backward"
- "If all launch conditions are met, proceed with launch"
Conditional statements let your code take different paths depending on whether a condition is True or False. This is one of the most powerful concepts in programming!
The if Statement
The if statement is the simplest conditional. It says: "if this condition is True, run
this block of code."
Syntax rules:
- Start with the keyword
if - Follow with a condition (something that evaluates to True or False)
- End the line with a colon
: - Indent the code block that should run if the condition is True
Indentation Matters!
Python uses indentation (typically 4 spaces) to define code blocks. All lines at the same
indentation level belong to the same block. This is different from languages that use braces
{}.
if...else Statements
Use else to specify what happens when the condition is False:
if...elif...else for Multiple Conditions
When you have more than two possibilities, use elif (short for "else if"):
Combining Conditions
7. Loops: Repeating Operations
Imagine you need to calculate position at 1000 different time points, or check conditions for 50 particles. Writing 1000 or 50 lines of code would be tedious! Loops solve this by letting you repeat a block of code multiple times.
There are two main types of loops:
- for loops: Use when you know how many times to repeat ("do this 10 times" or "do this for each item in a list")
- while loops: Use when you repeat until a condition becomes false ("keep going until y < 0")
for Loops: Known Number of Iterations
A for loop iterates over a sequence (like a list or range of numbers) and runs the
indented code block once for each item. The syntax is:
for variable in sequence:
# code to repeat (indented)
Each time through the loop, variable takes on the next value from the sequence. The
range() function is commonly used to generate number sequences.
Iterating Over Lists
Physics Example: Projectile Motion
while Loops: Condition-Based Iteration
Use while loops when you don't know in advance how many iterations you need—continue
until a condition becomes False.
break and continue
8. Functions: Reusable Code
A function is a named block of code that performs a specific task. Functions let you write code once and reuse it many times—essential for physics where you repeatedly apply the same formulas.
Defining Functions
You define a function with the def keyword, followed by the function name, parameters in
parentheses, and a colon. The function body is indented.
Return Values
Functions can compute and return a value for use elsewhere:
Default Parameters
Why Functions Matter
- Reusability: Write formulas once, use many times
- Organization: Break complex problems into smaller pieces
- Debugging: Test and fix each function independently
- Readability:
kinetic_energy(m, v)is clearer than0.5 * m * v**2
9. Error Handling
Errors happen—invalid input, division by zero, files not found. Instead of letting your program
crash, you can handle errors gracefully using try...except blocks.
Common Error Types
try...except Blocks
Put risky code in a try block. If an error occurs, Python jumps to the matching
except block instead of crashing.
Handling Multiple Errors
10. Working with Files
In physics, you'll often need to save simulation results or read experimental data from files. Python makes file I/O straightforward.
Note
File operations shown here are simulated in this browser environment. On your local Python installation, these would create real files.
Writing Files
Use open() with mode 'w' to write. The with statement ensures
the file is properly closed.
Reading Files
Real-World Tip
For complex data files, use libraries like Pandas which can read CSV, Excel, and
many other formats with a single line: data = pd.read_csv("file.csv")
11. Modules and Scientific Libraries
Python's real power for physics comes from its ecosystem of scientific libraries. A module is a file containing Python code you can import and use. A library or package is a collection of related modules.
The math Module
Python's built-in math module provides mathematical functions:
Key Scientific Libraries
These are the essential libraries you'll use for physics:
- NumPy: Fast numerical arrays and mathematical operations
- SciPy: Scientific algorithms (integration, optimization, etc.)
- Matplotlib: Plotting and visualisation
- Pandas: Data analysis and manipulation
Browser Limitation
NumPy is available in this browser environment! SciPy and Matplotlib require local installation.
Using the math Module for Physics
12. Putting It All Together: Physics Simulations
Now let's combine everything you've learned to build complete physics simulations. These examples demonstrate real scientific computing.
Complete Projectile Motion Simulator
Simple Harmonic Oscillator
Orbital Mechanics Calculator
Numerical Integration: Euler Method
Congratulations!
You've completed the Interactive Python for Physicists course! You now have the skills to:
- Write Python programs from scratch
- Work with variables, data structures, and functions
- Implement loops and conditional logic
- Handle errors gracefully
- Build physics simulations
Keep practising by modifying the examples above—change parameters, add features, and explore!