= 5.0
a = 3
b = a + b c
2 Variables and Numbers
2.1 Variables
When performing mathematical operations, it is often desirable to store the values in variables for later use instead of manually typing them back in each time you need to use them. This will reduce effort because small changes to variables can automatically propagate through your calculations.
Attaching a value to a variable is called assignment and is performed using the equal sign (=), as demonstrated in the cell below:
2.1.1 Variable naming convention
There are some rules for allowed variable names in Python. They are as follows:
- Variable names must begin with a letter or an underscore (
_
) - Variables names must only contain letters, numbers, and underscores.
- Variable names cannot contain spaces.
- Variables names cannot be a word reserved by Python for something else. These words are:
Python | reserved | words | ||
---|---|---|---|---|
and | as | assert | break | class |
continue | def | del | elif | else |
except | False | finally | for | from |
global | if | import | in | is |
lambda | None | nonlocal | not | or |
pass | raise | return | True | try |
why | with | yield |
The cell below contains some allowed variable names and some that are not allowed.
To Do:
- Determine which variable names are allowed and which are not in the cell below.
- What does Python do if you try to define a variable using a name that is not allowed?
= 3
my1variable 1stvariables = 2
= 3
a big constant = 1e8 a_big_constant
It is also a good practice to make variable names meaningful. For example, in the cell below we calculate \(E = mc^2\) using two choices for variable assignments. In one case, it is easy to determine what the calculation is and in the other it isn’t.
# Good Variable Names
= 1.6
mass_kg = 3.0e8
light_speed = mass_kg * light_speed**2
energy
# Poor Variable Names
= 1.6
a = 3.0e8
b = a * b**2 c
2.2 Numbers: Integers and Floats
There are two types of numbers in Python - floats and integers. Floats, short for “floating point numbers,” are values with decimals in them. They may be either whole or non-whole numbers such as 3.0 or 1.2, but there is always a decimal point. Integers are whole numbers with no decimal point such as 2 or 53.
Mathematical operations that only use integers and evaluate to a whole number will generate an integers (except for division). All other situations will generate a float. See the example cell below.
= 24
a = 6
b = 0.3
d = a + b # Produces an integer.
e = a + d # Produces a float
f = a * b # Produces a ???
g = a / b # Produces a ??? h
To Do:
- For each of the mathematical operations above guess what type of number the result will be.
- Use
type()
function will tell you what kind of number a variable is.)
# Python Code Here!
Integers and floats can be inter-converted to each other using the int()
and float()
functions.
int(3.0)
float(4)
4.0
The distinction between floats and ints is often a minor detail. Occasionally, a function will require that an argument be a float or an int but usually you won’t have to worry about which one you use.
Below you will find some other common mathematical operations that can be performed on numerical variables.
= 20
a = 10
b = a + b
c = a/b
d = a//b
r = a % b
r = a * b
e = c**4 f
To Do:
- Use print statements to investigate what each operation does.
- Guess what type of number you expect the result to produce (int or float) and then check yourself?
- Add comments next to each line (Use
#
to start a comment) explaining that operation.
# Python Code Here!
2.2.1 Augmented Assignment
Augmented assignment is a shortened way to make a simple modification to a variable. For example, if we want to increase the value of a variable by 10, one way to do it would be like this.
= 5
a = a + 10 a
This is certainly not difficult, but it does involve typing the variable twice which becomes cumbersome as your variable name gets longer. Alternatively, we can accomplish the same thing with the +=
operator.
= 5
a += 10 a
Augmented assignment can be used with addition, subtraction, multiplication, and division as shown in the code cell below.
= 7
a += 3
a -= 1
a *= 4
a /= 3 a
To Do:
- Predict what the final result of
a
will be in the code cell above.- Add an appropriately-place
- If you were wrong, pow-wow with your neighbor until you understand.
# Python Code Here!
2.2.2 Compound Assignment
At the beginning of a program or calculation, it is often necessary to define a set of variables. Each variable may get it’s own line of code, but if there are a lot of variables, this can begin to clutter your code a little. An alternative is to assign multiple variables on a single line. In the code below, we assign the atomic mass of the first three elements.
= 1.01, 4.00, 5.39 H, He, Li
To Do:
- Use print statements to verify that each variable was assigned it’s own value.
- Add assignments for the atomic masses of the next three elements on the periodic table.
# Python Code Here!
2.2.3 Large numbers
Sometimes you find yourself working with large numbers in your calculation. Maybe your calculation involves the use of ten billion, which has 10 zeros in it. It can be difficult to look at all of those zeros with no commas to help break it up. In those cases, you can use an underscore (_
) in place of the comma, as shown below.
= 10000000000 # This is tough to look at.
myLargeNumber = 10_000_000_000 # This is easy to read
myLargeNumber
= 5000000.6 # This is tough to read
myLargeFloat = 5_000_000.6 # This is easy to read myLargeFloat
2.2.4 Very Large Numbers
If your number is very large or very small ( \(20-30\) zeros), you would probably rather not have to type all of the zeros at all, even if you can break it up with the underscores. For example, the Boltzmann constant, which comes up in thermodynamics, has a value equal to
\[ 1.38 \times 10^{-23}\]
We can avoid typing all those zeros by using scientific notation when defining the variable. (see example below) This is super handy for very large and very small numbers. (Numbers of both variety show up frequently in physics!)
= 1.38e-23 kB
2.2.5 Python functions
In addition to basic mathematical functions, python contains several mathematical functions. As in mathematics, a function has a name (e.g. f) and the arguments are places inside of the parenthesis after the name. The argument is any value or piece of information fed into the function. In the case below, f requires a single argument x. \[f(x)\]
In the cell below, you will find several useful Python functions.
abs(-5.5)
float(2)
int(5.6)
print(1.26e-6)
round(-5.51)
str(3.2)
1.26e-06
'3.2'
In addition to Python’s native collection of mathematical functions, there is also a math
module with more mathematical functions. Think of a module as an add-on or tool pack for Python just like a library. The math
module comes with every installation of python and can be imported (i.e. activated) using the import math
command. After the module has been imported, any function in the module is called using math.function()
where function
is the name of the function. Below is a list of commonly-used functions inside the math module
. Carefully look at each of them and guess what they mean.
import math
4)
math.sqrt(4.3)
math.ceil(1.5)
math.cos(1.5)
math.sin(3.14)
math.tan(1)
math.asin(1/2)
math.acos(2)
math.atan(6.28)
math.degrees(
math.e5)
math.exp(4)
math.factorial(200)
math.log(1000)
math.log10(360)
math.radians(
math.pipow(2,8) math.
256.0
To Do:
- Use print statements to figure out what each function in the code cell above does. Pay special attention to trigonometric function. Do these functions expect the argument to be in radians or degrees?
- Add comments to remind yourself for later.
# Python Code Here!
There are other ways to import functions from modules. If you only want to use a single function inside the module, you can selectively import it using from
, as shown below.
from math import radians
4) radians(
0.06981317007977318
2.3 Errors In Python
When you are learning to write code, you will inevitably run into errors. Seeing a block of red text can be intimidating at first, but it’s important to remember that errors are not failures; they are helpful signs. The error message is simply Python’s way of telling you that it couldn’t understand your instructions and often gives you a very specific clue about what went wrong.
Learning to read these messages is a fundamental skill that will turn you into a more effective programmer. Let’s look at some of the most common errors you will encounter on your journey.
2.3.1 Syntax Error
A SyntaxError
is the most common type of error for beginners. It means you have broken a grammar rule of the Python language. Just like a sentence in English needs correct punctuation to make sense, a line of Python code needs correct syntax.
: Missing punctuation, like a colon :, a parenthesis ), or a quotation mark “.
In the example below, we forget to close the parentheses for the print function.
# We are trying to print a message, but we forgot the closing parenthesis.
print("This line has a syntax error"
Cell In[19], line 2 print("This line has a syntax error" ^ _IncompleteInputError: incomplete input
2.3.2 Indentation Error
Python is unique because it uses whitespace (specifically, the spaces at the beginning of a line) to group code together. An IndentationError
means that the spacing in your code is not correct or consistent.
: Forgetting to indent code that belongs inside a loop, function, or if statement.
# The line below should be indented, because it belongs inside the for loop.
for i in range(5):
print(i)
Cell In[20], line 3 print(i) ^ IndentationError: expected an indented block after 'for' statement on line 2
You can also get an IndentationError
if there are multiple lines indented but their indentation levels are not consistent, as shown below.
# Indentation error because the lines in the loop are not all indented
# to the same position
for i in range(10):
print(i)
print(i**2)
Cell In[21], line 5 print(i**2) ^ IndentationError: unexpected indent
2.3.3 NameError
A NameError
occurs when you try to use a variable or function that Python doesn’t recognize.
: A typo in a variable name or trying to use a variable before you have assigned it a value.
# We create a variable called 'initial_velocity'.
= 20
initial_velocity
# But then we make a typo when trying to print it. Python doesn't know what 'initial_velocite' is.
print(initial_velocite)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[22], line 5 2 initial_velocity = 20 4 # But then we make a typo when trying to print it. Python doesn't know what 'initial_velocite' is. ----> 5 print(initial_velocite) NameError: name 'initial_velocite' is not defined
Since Python executes code sequentially: the first line gets executed first, then the second line, etc., you can get a NameError
if you try to use a variable before it is defined, as shown below.
= 5.22
dx
= dx/dt # A NameError occurs at this line because dt is not yet defined.
v
= 0.4 dt
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[23], line 3 1 dx = 5.22 ----> 3 v = dx/dt # A NameError occurs at this line because dt is not yet defined. 5 dt = 0.4 NameError: name 'dt' is not defined
2.3.4 TypeError
A TypeError
means you are trying to do an operation with a data type that doesn’t support it. It’s like trying to add a word to a number—it just doesn’t make sense.
: Trying to combine incompatible types, like adding a string and an integer.
# You can't directly add a number (an integer) to a word (a string).
# Python doesn't know if you mean to do math or combine text.
= "The answer is: " + 5 message
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 3 1 # You can't directly add a number (an integer) to a word (a string). 2 # Python doesn't know if you mean to do math or combine text. ----> 3 message = "The answer is: " + 5 TypeError: can only concatenate str (not "int") to str
2.3.5 IndexError
An IndexError
happens when you try to access an item in a list using an index that is out of bounds.
: Forgetting that list indices start at 0. For a list of 3 items, the only valid indices are 0, 1, and 2.
# This list has three items.
= ["Mercury", "Venus", "Earth"]
planets
# The valid indices are 0, 1, and 2.
# By asking for index 3, we are asking for a fourth item that doesn't exist.
print(planets[3])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[25], line 6 2 planets = ["Mercury", "Venus", "Earth"] 4 # The valid indices are 0, 1, and 2. 5 # By asking for index 3, we are asking for a fourth item that doesn't exist. ----> 6 print(planets[3]) IndexError: list index out of range
2.3.6 FileNotFoundError
This is a very common error when you start working with data. It simply means that you are trying to open a file that Python cannot find at the location you specified.
: A typo in the filename or the file not being in the same folder as your script.
# Python will look in the current folder for a file with this name.
# If it can't find it, it will raise this error.
with open("data_that_does_not_exist.csv") as f:
print(f.read())
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[26], line 3 1 # Python will look in the current folder for a file with this name. 2 # If it can't find it, it will raise this error. ----> 3 with open("data_that_does_not_exist.csv") as f: 4 print(f.read()) File ~/environments/lammps_env/lib/python3.13/site-packages/IPython/core/interactiveshell.py:343, in _modified_open(file, *args, **kwargs) 336 if file in {0, 1, 2}: 337 raise ValueError( 338 f"IPython won't let you open fd={file} by default " 339 "as it is likely to crash IPython. If you know what you are doing, " 340 "you can use builtins' open." 341 ) --> 343 return io_open(file, *args, **kwargs) FileNotFoundError: [Errno 2] No such file or directory: 'data_that_does_not_exist.csv'