📓 About This Tutorial

This webpage is a static view of an interactive Jupyter Notebook tutorial. To get the full interactive experience where you can run Python code, modify examples and complete exercises, click the "Open in Colab" button. This will access the Google Colab notebook from a GitHub repository github.com/dchappell2/Computational-Physics and open it in Google Colab. You will need a Google account if you want to open it in Colab.

Note: You can download a pdf of the lecture slides for this chapter here: Chapter 0-3 slides

Chapter 1 - Variables

Objectives:

1.0 Use variables to store values

name = "Marie"
age = 20

1.1 Use print() to display variables

print(name)

If you see an error message, it might be because the initial code cell defining the age and name variables was never run. If so, go back, run it and then re-run the print statement.

You can also include descriptive text and multiple variables in the print statement. For example, run the following code cell:

print(name, 'is', age, 'years old')
Marie is 20 years old

You should see the output displayed below the code cell. Notice the following:

BTW, the the print statement is the first example of something called a function. The function takes arguments, which are the variable names and the strings enclosed in quotes. We'll talk more about functions later.

1.2 Variables persist between cells

The previous examples show that variables defined in one cell can be used in cells farther down the page. In the above example, the variables age and name were defined in one cell and used in a print statement in a different cell.

One consequence of this "memory" is that after the notebook is run once, all the variables will be remembered the next time the code is run. While this normally isn't an issue for well-writted code, it can cause unexpected results if variables aren't properly defined the first time they are used. If you suspect that this effect may be causing problems, you have an option:

1.3 Variables must be created before they are used

Run the following code block to see what happens when you try to print out a variable that hasn't been defined

print(first_name)

✅ Skill Check 1

To correct this error, double-click on the code cell and replace "first_name" with "name". Then run the cell. The error message should disappear and you should see "Maria" displayed.

🟩

1.4 Order of execution

Be aware that if you run code cells out of order in a Jupyter document, strange things can happen. I recommend the following:

1.5 Variables can be used in calculations

Consider the following code that defines the width and height of a rectangle, calculates the area and then displays the result. Run the following code cell:

width = 10              # in meters
height = 5              # in meters
area = width * height   # calculate area of rectangle in meters^2
print("area =",area)    # display result

Suppose you received revised information that the triangle is actually 5 meters wider than you thought. You could update the width variable as follows (run the following code cell):

width = width + 5

This can be a confusing statement to non-programmers. If interpreted as a math equation, one could "cancel" the width variable from both sides of the equation and be left with 0 = 5 🙁. But, remember:

If you want to know the area of the revised rectangle, you will need to recalculate the area (run the following):

area = width * height           # calculate area of revised rectangle in meters^2
print("revised area =",area)    # display result

Remember that variables are updated in the order that they are executed (i.e. down the page). Thus, if we change the value of a variable, we would need to redo any calculations that depend on it.

1.6 Variable names should be descriptive

Variable names should be descriptive, i.e. mass, velocity, etc. or the should correspond to typical mathematical variables, i.e. m, v, etc. Variable names cannot contain spaces. If you want a complex variable name, you can use the underscore _ in place of a space. Another option is "Camel" notation, where capitalization can be used. See the following examples:

seconds_per_minute = 60   # use underscore
secondsPerMinute = 60     # "Camel" notation

Sometimes it is useful to define fundamental constants in MKS units when doing physics calculations. In Python, scientific notation is written as 1.23e4 for $1.23\times 10^4$. The e proceeds the power of ten. Here are some standard fundamental constants. Run this code cell to create these variables.

🔆 List of fundamental physical constants

c = 299792458            # definition of the speed of light in m/s
h = 6.626e-34            # Planck's constant (J s)
hbar = 1.0546e-34        # "h bar" = h / 2*pi  (J s)
G = 6.6743e-11           # Gravitational constant (m^3/kg/s^2
e = 1.602177e-19         # fundamental charge (C)
me = 9.10938e-31         # mass of electron (kg)
epsilon0 = 8.854188e-12  # vacuum permittivity (F/m)

After running the above code cell, you can now use these constants in calculations.

🔆 Example: Rest energy

For example, let's use Einstein's famous $E=m c^2$ to calculate the energy (in Joules) contained in my cat ($m=5$ kg). Of course this energy can ony be released if my cat meets an anti-cat made purely of antimatter, but...

m = 5                # mass of my cat in kg
E = m * c**2         # Einstein's formula. We use the value of c defined above
print(m,"kg is equivalent to",E,"Joules")  # display the result

✅ Skill Check 2

A light year (ly) is defined as the distance light can travel in one year: $ly= c\cdot year$, where $c=$ the speed of light and $year=$ length of a year. Follow these steps to calculate the length of a light year in meters:

$ly= c\cdot year$

1.7 Prompting the user for input

Sometimes, it is convenient to have the program prompt the user for input, rather than defining variables by hand. Python provides the input() command to do this. Here's how the input() function works:

The following prompts the user to enter their favorite number and then displays a message back to the user:

number = input("Enter your favorite number: ")
print(number, "is my favorite number too!")

✅ Skill Check 3

Write some code to prompt the user to enter the name of their favorite physicist. Print a message to the screen that says "Your favotite physicist is ___", where ___is the name the user entered.

1.8 Possible Errors

Error messages are a normal part of coding. Even though they can be quite vexing at times, think of them as the computer's way of helping you succeed! Overcoming anxiety over error messages is a big step on the path to coding enlightenment.

Here are some common errors that you might encounter and ways to fix them:

Variable is not defined

print(hot_dog)

Missing quote

Google Colab has auto-completion and often tries to help you remember to include closing quotes and parentheses. But sometimes errors still arise.

For example, if you forget to include a closing quote in tha print statement, you can get the cryptic message "unterminated string literal". Run the following statement as is:

print("hello)

Missing parenthesis

print("hello"

Key Points

This tutorial is a modified adaptation of "Python for Physicists"

© Software Carpentry