Python Basics I#
Welcome to Python Basics I, where you’ll learn the fundamental building blocks of Python:
Printing and running Python code
Basic data types (integers, floats, booleans, strings)
Basic operators (arithmetic, comparison, logical)
Input and output
Control flow (if statements, for/while loops)
By the end of this notebook, you should be comfortable writing simple Python scripts, understanding indentation, and implementing small programs that use conditionals and loops.
Preliminary Setup#
No need to install if you are using Google Colab.
If you want to run Python code on your own devices, JupyterLab Desktop is recommended for this course. You can download it from jupyterlab/jupyterlab-desktop.
Let’s get started by printing a simple message to the screen.
Hello, Physics!#
This is the traditional “Hello, World!” program, adapted for physics.
print("Hello, Physics!")
If you run the cell above, you should see Hello, Physics! printed below it.
1. Python Basic Syntax & Indentation#
Python uses indentation (instead of braces {}) to define code blocks. For example:
if True:
print("This is inside the if-statement.")
print("Note the indentation!")
Key Points:
A code block is typically indented by 4 spaces.
If indentation is off, Python will raise an
IndentationError.
2. Making graphs#
First we need to import a couple libraries: numpy and matplotlib. Libraries are collections of python functions that other people have written. We will frequently need these two libraries for doing physics.
# for mathematics and working with arrays
import numpy as np
# for plotting
import matplotlib.pyplot as plt
Python completely ignores any line that begins with #. These lines are called ‘comments’, and they are a critical part of all of your code.
Now let’s pick some points to plot. We’ll store the x-values in the variable x and the y-values in the variable y.
We store the values as arrays, which are a useful data type for math and plotting and working with large collections of numbers. Notice we use numpy to define the array (through it’s nickname “np”), since arrays aren’t built into python by default.
x = np.array([1,2,3,4,5])
y = x+3
print (y)
Let’s plot it! We need matplotlib.pyplot to do this, which we nicknamed “plt”.
plt.plot(x,y,'r*')
The graph is ugly, so let’s clean it up a bit.
Matplotlib includes all sorts of functions to clean up and label plots. Let’s try some of them:
plt.plot(x,y,'g+')
plt.title('Title X')
plt.xlabel('Time (days)')
plt.ylabel('Distance (miles)')
plt.xlim(0, 6)
plt.ylim(2, 10);
Let’s take a moment to talk about what’s we’ve done so far. For starters, x and y are variables. Variables in Python are essentially storage bins: x in this case is an address which points to a memory bin somewhere in the computer that contains an array of 5 numbers. Python variables can point to bins containing just about anything: different types of numbers, lists, files on the hard drive, strings of text characters, true/false values, other bits of Python code, whatever! When any other line in the Python script refers to a variable, Python looks at the appropriate memory bin and pulls out those contents. When Python gets the line
y = x+3
It pulls out the x array, adds three to everything in that array, puts the resulting array in another memory bin, and makes y point to that new bin. The plot command plt.plot(x,y,’rx’) creates a new figure window if none exists, then makes a graph in that window. The first item in parenthesis is the x data, the second is the y data, and the third is a description of how
the data should be represented on the graph, in this case red x symbols.
Let’s build a fancier plot this time.
# this linspace function generates 100 values evenly spaced between 0.0 and 10.0
time = np.linspace(0.0, 10.0, 100)
# use exponential and sine functions from numpy to define the y-values (height) from the x-values (time)
height = np.exp(-time/3.0) * np.sin(time*3)
# plot time vs height, with magenta triangles for each point, connected by lines
plt.plot(time, height, 'm-^')
# on the same figure, plot time vs a sinusoid with constant height, and connect the points with green lines
plt.plot(time, 0.7*np.sin(time*3), 'g-')
# add a legend to label the different curves
plt.legend(['damped', 'constant amplitude'], loc='upper right')
# label the x-axis
plt.xlabel('Time (s)')
plt.ylabel('Height')
Importing and graphing real data#
It’s unlikely that you would be particularly excited by the prospect of manually typing in data from every experiment or simulation. The whole point of computers, after all, is to save us effort! Python can read data from text files quite well. We’ll discuss this ability more in later, but for now here’s a quick way of reading data files for graphing.
Suppose we have a text file with real data, and we want to graph it. We need to find the file, and then we need to import it into python.
First, we need to download the data file ‘microphones.txt’. The exclamation mark (!) allows users to run shell commands from inside a Jupyter Notebook code cell. Simply start a line of code with ! and it will run the command in the shell.
Example: !pwd will print the current working directory. Here, we use the command ‘wget’ to downloand the data file.
from pathlib import Path
Path.cwd()
from pathlib import Path
sorted(item.name for item in Path.cwd().iterdir())[:10]
from urllib.request import urlretrieve
url = "https://zhuli.name/files/microphones.txt"
urlretrieve(url, "microphones.txt")
from pathlib import Path
"microphones.txt" in [item.name for item in Path.cwd().iterdir()]
#frequency, mic1, mic2 = np.loadtxt('microphones.txt', unpack = True)
data = np.loadtxt('microphones.txt', unpack=True)
print (data)
frequency, mic1, mic2 = np.loadtxt('microphones.txt', unpack = True)
print(mic1)
print(len(mic1))
plt.plot(frequency, mic1)
Now let’s make a labeled plot, commenting our code for clarity:
# plot frequency vs mic1 amplitude with a red curve, and
# frequency vs mic2 amplitude with a blue curve
plt.plot(frequency, mic1, 'r-', frequency, mic2*(-2.5)+5, 'b-')
# label the plot
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude(arbitrary units)')
plt.legend(['Microphone 1', 'Microphone 2']);
3. Variables and Data Types#
3.1 Variables#
A variable is a name that refers to a value. In Python, you assign variables using =:
x = 10 # integer
y = 3.14 # float
name = "Alice" # string
# Example:
x = 10
y = 3.14
name = "Alice"
print("x =", x)
print("y =", y)
print("name =", name)
t = False
print (t)
3.2 Data Types#
Common data types in Python:
Integer (
int) – whole numbers (e.g., 42).Float (
float) – decimal or real numbers (e.g., 3.14).Boolean (
bool) –TrueorFalse.String (
str) – sequence of characters in quotes (e.g., “Hello”).
Use type() to check:
a = 5
b = 2.718
c = "Hello"
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
# Let's test type() ourselves
a = 5
b = 2.718
c = "Hello"
d = True
e = 1+2j
print("a =", a, ", type:", type(a))
print("b =", b, ", type:", type(b))
print("c =", c, ", type:", type(c))
print("d =", d, ", type:", type(d))
print("e =", e, ", type:", type(e))
print ('real ', e.real)
print ('imag ', e.imag)
3.3 String Operations#
Strings are sequences of characters. Python provides many useful operations for working with strings:
## String concatenation
first = "Computational"
last = "Physics"
full = first + " " + last # "Computational Physics"
## f-strings (formatted strings) - very useful for physics!
mass = 9.109e-31
print(f"Electron mass: {mass:.3e} kg") # Electron mass: 9.109e-31 kg
## String methods
text = " Hello Physics "
print(text.strip()) # "Hello Physics" (removes whitespace)
print(text.lower()) # " hello physics "
print(text.upper()) # " HELLO PHYSICS "
# Try string operations
course = "Computational"
subject = "Physics"
full_name = course + " " + subject
print(full_name)
# f-strings for formatted output (very useful!)
c = 299792458 # speed of light in m/s
print(f"Speed of light: {c} m/s")
print(f"Speed of light: {c:.2e} m/s") # scientific notation
3.4 Type Conversion#
You often need to convert between data types. This is especially important when reading user input (which is always a string).
## String to numbers
x = int("42") # string to int: 42
y = float("3.14") # string to float: 3.14
## Numbers to string
z = str(299792458) # int to string: "299792458"
## Why this matters for input()
speed = float(input("Enter speed: ")) # Convert input to float
# Type conversion examples
num_str = "42"
num_int = int(num_str)
print(f"{num_str} as integer: {num_int}, type: {type(num_int)}")
pi_str = "3.14159"
pi_float = float(pi_str)
print(f"{pi_str} as float: {pi_float}, type: {type(pi_float)}")
# Be careful! This will cause an error:
# int("3.14") # Can't convert float string directly to int
3.5 List Basics#
Lists store multiple values in a single variable. They are essential for working with data.
## Creating lists
measurements = [1.2, 3.4, 5.6, 7.8]
names = ["electron", "proton", "neutron"]
mixed = [1, "two", 3.0, True] # Can mix types (but usually don't)
## Accessing elements (0-indexed!)
print(measurements[0]) # First element: 1.2
print(measurements[-1]) # Last element: 7.8
## List length
print(len(measurements)) # 4
## Adding elements
measurements.append(9.0) # Add to end
# List basics
masses = [9.109e-31, 1.673e-27, 1.675e-27] # electron, proton, neutron masses in kg
particles = ["electron", "proton", "neutron"]
print(f"First particle: {particles[0]}")
print(f"Its mass: {masses[0]:.3e} kg")
print(f"Number of particles: {len(particles)}")
# Add a new particle
particles.append("muon")
masses.append(1.884e-28)
print(f"Updated list: {particles}")
4. Operators#
4.1 Arithmetic Operators#
+(addition)-(subtraction)*(multiplication)/(division, float result)//(floor division, integer result)%(modulus, remainder)**(exponentiation)
Example:
x = 5
y = 2
print(x + y) # 7
print(x - y) # 3
print(x * y) # 10
print(x / y) # 2.5
print(x // y) # 2
print(x % y) # 1
print(x ** y) # 25
# Let's try arithmetic:
x = 5
y = 2
print("x + y =", x + y)
print("x - y =", x - y)
print("x * y =", x * y)
print("x / y =", x / y)
print("x // y =", x // y)
print("x % y =", x % y)
print("x ** y =", x ** y)
4.2 Comparison Operators#
Compare two values; results are True or False.
>(greater than)<(less than)==(equal to)!=(not equal to)>=(greater or equal)<=(less or equal)
Example:
x = 5
y = 2
print(x > y) # True
print(x < y) # False
print(x == y) # False
print(x != y) # True
x = 5
y = 2
print("x > y?", x > y)
print("x < y?", x < y)
print("x == y?", x == y)
print("x != y?", x != y)
print("x >= y?", x >= y)
print("x <= y?", x <= y)
z = 2
print(x>y and z>y)
print(x>y or z>y)
4.3 Logical (Boolean) Operators#
andornot
Example:
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
p = True
q = False
print("p and q =", p and q)
print("p or q =", p or q)
print("not p =", not p)
6. Input/Output#
6.1 Output with print()#
We’ve already been using print(), which sends text to the console.
6.2 Reading Input with input()#
We can prompt the user and read input from the console with input(). Note that input() returns a string, so you must convert it to a number if needed.
# Try running this cell. Enter a number at the prompt.
user_input = input("Enter a number: ")
print("You entered:", user_input, "which is of type", type(user_input))
x = float(user_input) # Convert string to float
print("You entered:", x, "which is of type", type(x))
7. Control Flow#
7.1 if-elif-else Statements#
Used to execute code conditionally.
temperature = 15
if temperature < 0:
print("It's freezing!")
elif temperature < 20:
print("It's chilly.")
else:
print("The weather is nice.")
temperature = 15
if temperature < 0:
print("It's freezing!")
elif temperature < 20:
print("It's chilly.")
else:
print("The weather is nice.")
7.2 for Loops#
Loop over a sequence or range.
for i in range(5):
print("i =", i)
You can also iterate over elements in a list or string:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i in range(5):
print("i =", i)
print ('------')
for i in [3,5,8,1,5]:
print("i =", i)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)
7.2.1 The range() Function in Detail#
The range() function is very flexible:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1, stepping by step
Examples:
range(5) # 0, 1, 2, 3, 4
range(2, 6) # 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8 (even numbers)
range(5, 0, -1) # 5, 4, 3, 2, 1 (countdown!)
# range() examples
print("range(5):")
for i in range(5):
print(i, end=" ")
print()
print("\nrange(2, 6):")
for i in range(2, 6):
print(i, end=" ")
print()
print("\nrange(0, 10, 2) - even numbers:")
for i in range(0, 10, 2):
print(i, end=" ")
print()
print("\nrange(5, 0, -1) - countdown:")
for i in range(5, 0, -1):
print(i, end=" ")
print("\nBlastoff!")
7.2.2 break and continue Statements#
Control loop execution:
break: Exit the loop immediatelycontinue: Skip to the next iteration
## break example: stop when we find what we want
for n in range(1, 100):
if n > 10 and n % 2 == 0:
print(f"First even number > 10: {n}")
break
## continue example: skip certain values
for x in range(5):
if x == 2:
continue # skip x=2
print(x) # prints 0, 1, 3, 4
# break: find first number divisible by 7 greater than 50
for n in range(1, 100):
if n > 50 and n % 7 == 0:
print(f"Found: {n}")
break
print("---")
# continue: skip negative values in data processing
data = [1.5, -2.3, 3.7, -0.5, 4.2]
print("Processing only positive values:")
for value in data:
if value < 0:
continue # skip negative
print(f" {value}")
7.3 while Loops#
Repeat a block of code as long as a condition is True.
count = 0
while count < 3:
print("Count is:", count)
count += 1
count = 0
while count < 3:
print("Count is:", count)
# count += 1
count = count + 1
8. Mini-Exercises#
Try these to reinforce what you’ve learned.
Exercise: Conditionals – Positive, Negative, or Zero#
Prompt the user to input a number.
Check if the number is positive, negative, or zero.
Print a message accordingly.
num = float(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
8.5 Common Beginner Errors#
Understanding error messages will save you hours of frustration! Here are the most common errors:
IndentationError#
Python uses indentation to define code blocks. Inconsistent indentation causes errors.
if True:
print("This will fail!") # Missing indentation!
NameError#
Trying to use a variable that doesn’t exist.
print(undefined_variable) # NameError: name 'undefined_variable' is not defined
TypeError#
Operating on incompatible types.
result = "5" + 3 # TypeError: can only concatenate str to str
## Fix: result = int("5") + 3 OR result = "5" + str(3)
SyntaxError#
Invalid Python syntax (missing colons, parentheses, quotes, etc.).
if x > 5 # SyntaxError: missing colon
print("hi" # SyntaxError: missing closing parenthesis
# Uncomment each line one at a time to see the errors:
# NameError:
# print(my_undefined_variable)
# TypeError:
# result = "5" + 3
# The fix for TypeError:
result = int("5") + 3
print(f"Fixed result: {result}")
8.6 Physics Examples#
Let’s apply what we’ve learned to physics problems!
# Kinematics: Calculate final velocity
v0 = 10.0 # initial velocity (m/s)
a = -9.8 # acceleration due to gravity (m/s²)
t = 2.0 # time (s)
v = v0 + a * t
print(f"Initial velocity: {v0} m/s")
print(f"After {t} seconds: {v} m/s")
# Unit conversion with a loop
distances_km = [1, 5, 10, 42.195] # marathon!
print("Distance Conversion:")
print("-" * 25)
for d in distances_km:
miles = d * 0.621371
print(f"{d:8.3f} km = {miles:10.3f} miles")
# Calculate kinetic energy for different velocities
mass = 1.0 # kg
velocities = [1, 2, 5, 10, 20] # m/s
print(f"Kinetic Energy (mass = {mass} kg)")
print("-" * 30)
for v in velocities:
KE = 0.5 * mass * v**2
print(f"v = {v:2} m/s → KE = {KE:6.1f} J")
9. Additional Practice#
Try writing small scripts that:
Sum the squares of the first 10 integers.
Check if a given year is a leap year (divisible by 4 but not by 100, unless also by 400).
Create a multiplication table using nested loops.
10. Summary & Next Steps#
We covered:
How to print in Python.
Basic data types and variables.
Operators (arithmetic, comparison, logical).
Input/Output.
Control flow (
if-elif-else,for,while).
You now have a solid foundation in Python Basics I. In the next lesson, we’ll dive deeper into data structures (lists, tuples, dictionaries) and learn about functions—the building blocks for writing organized, reusable code.
10. Using the math Module#
Python’s built-in math module provides mathematical functions and constants. This is essential for physics calculations!
import math
# Mathematical constants
print(f"π = {math.pi}")
print(f"e = {math.e}")
# Trigonometric functions (input in radians!)
print(f"\ncos(π) = {math.cos(math.pi)}")
print(f"sin(π/2) = {math.sin(math.pi/2)}")
# Other useful functions
print(f"\nsqrt(2) = {math.sqrt(2)}")
print(f"log(e) = {math.log(math.e)}")
print(f"log10(100) = {math.log10(100)}")
Getting Help#
Use help() to learn about any function or module:
# Get help on a specific function
help(math.cos)
# Uncomment to see all functions in math module:
# help(math)
11. Summary & Next Steps#
In this lecture, we covered:
Making graphs with NumPy and Matplotlib
Variables and data types (int, float, bool, str, list)
String operations and f-strings for formatting
Type conversion between data types
Operators (arithmetic, comparison, logical)
Input/Output with
print()andinput()Control flow (
if-elif-else,for,while,break,continue)Common errors and how to fix them
The
mathmodule for mathematical functions
Next Lecture: Python Basics II#
Functions
More on lists and other data structures
File I/O
Error handling with try/except
5. Comments#
Single-line comments use
#.Multi-line strings/docstrings use triple quotes
"""...""".Example:
Comments help others (and your future self) understand the code.