2  Variables and Numbers

Jupyter Notebook

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:

a = 5.0
b = 3
c = a + b

2.1.1 Variable naming convention

There are some rules for allowed variable names in Python. They are as follows:

  1. Variable names must begin with a letter or an underscore (_)
  2. Variables names must only contain letters, numbers, and underscores.
  3. Variable names cannot contain spaces.
  4. 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:

  1. Determine which variable names are allowed and which are not in the cell below.
  2. What does Python do if you try to define a variable using a name that is not allowed?
my1variable = 3
1stvariables = 2
a big constant = 3
a_big_constant = 1e8

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
mass_kg = 1.6
light_speed = 3.0e8
energy = mass_kg * light_speed**2


# Poor Variable Names
a = 1.6
b = 3.0e8
c = a * b**2

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.

a = 24
b = 6
d = 0.3
e = a + b # Produces an integer.
f = a + d # Produces a float
g = a * b # Produces a ???
h = a / b # Produces a ???

To Do:

  1. For each of the mathematical operations above guess what type of number the result will be.
  2. Use print statements to verify your guesses and formulate a general rule that you can rely on. (Tip, the 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.

a = 20
b = 10
c = a + b 
d = a/b  
r = a//b
r = a % b
e = a * b
f = c**4

To Do:

  1. Use print statements to investigate what each operation does.
  2. Guess what type of number you expect the result to produce (int or float) and then check yourself?
  3. 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.

a = 5
a = a + 10

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.

a = 5
a += 10

Augmented assignment can be used with addition, subtraction, multiplication, and division as shown in the code cell below.

a = 7
a += 3
a -= 1
a *= 4
a /= 3

To Do:

  1. Predict what the final result of a will be in the code cell above.
  2. Add an appropriately-place print statement to see if you were correct.
  3. 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.

H, He, Li = 1.01, 4.00, 5.39

To Do:

  1. Use print statements to verify that each variable was assigned it’s own value.
  2. 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.

myLargeNumber = 10000000000 # This is tough to look at.
myLargeNumber = 10_000_000_000  # This is easy to read

myLargeFloat = 5000000.6 # This is tough to read
myLargeFloat = 5_000_000.6 # This is easy to read

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!)

kB = 1.38e-23

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. Here is a list of commonly-used functions inside the math module:

import math
math.sqrt(4)
math.ceil(4.3)
math.cos(1.5)
math.sin(1.5)
math.tan(3.14)
math.asin(1)
math.acos(1/2)
math.atan(2)
math.degrees(6.28)
math.e
math.exp(5)
math.factorial(4)
math.log(200)
math.log10(1000)
math.radians(360)
math.pi
math.pow(2,8)
256.0

To Do:

  1. 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?
  2. 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
radians(4)
0.06981317007977318

2.3 Flash Cards

  1. What are the rules for naming variables in Python?
  2. When will a mathematical calculation produce a float?
  3. When will a mathematical calculation produce an int?
  4. What is the best way to increase/decrease the value of a variable by a multiplicative factor (multiply it by a number)?
  5. What is the best way to increase/decrease the value of a variable by an additive constant (add a number to it)?
  6. When assigning large numbers to variables, what character can replace the “,” to separate the numbers into groups of three?
  7. How do you use scientific notation to assign a very large number to a variable?
  8. When using a trig function (\(\sin \theta\), \(\cos \theta\), \(\tan \theta\)), the number that is passed in must have what units?
  9. What does the math.radians function do?
  10. Where can you find King Benjamin’s address to his people?

2.4 Exercises

  1. Most (or all) of you have use Pythagorean’s theorem to calculate the hypotenuse of a right triangle. The theorem states that the lengths of a right triangle are related like this \(a^2 + b^2 = c^2\), where \(a\) and \(b\) are the lengths of the sides forming the right angle and \(c\) is the length of the hypotenuse. There is a Python function called hypot (found in a library called math) that will perform this calculation for your. Calculate the distance from the point \((-48,56)\) to the point \((23,81)\) using
    1. Pythogorean’s theorem
    2. The Python function hypot. To learn how to use the hypot function, visit the following documentation page and search for the explanation for the hypot function. Learning to read and understand online documentation is a skill that you you should develop.

Print out the result and check your answer with your neighbor’s answer.

# Python Code Here!
  1. Equations involing quadratic polynomials,like the one shown below, appear in science frequently.

\[ 5x^2 + 2x - 1 = 0\]

You may remember that the solution to this equation is given by the quadratic formula \[ x = {- b \pm \sqrt{b^2 - 4 a c} \over 2a}\] Solve the quadratic equation given above and print off the results. (There are two answers.) Then check with a classmate to verify that your answers match.

# Python Code Here!
  1. (Solar Mass) The mass of the sun can be calculated using the following formula:\[ M_\text{sun} = {4 \pi^2 (1 \text{ AU})^3\over G (1 \text{ yr})^2}\]
    The unit AU is called an astronomical unit of length and is defined to be the average distance between the sun and earth. \[ 1 \text{ AU} = 1.58\times 10^{-5} \text{ light years}\] where \(1 \text{ lightyear} = 9.5 \times 10^{15}\) m. The constant \(G\) is called the gravitational constant and has the value: \[ G = 6.674 \times 10^{-11} \text{ m}^3 \text{ kg}^{-1}\text{ s}^{-1}\] Calculate the mass of the sun (in kg) and display your result using a print statement. You should find a value of \(M_\text{Sun} = 2.01 \times 10^{30}\) kg.
# Python Code Here!
  1. (Projectile Motion) The range of a projectile is given by the equation:\[ d = {2 v^2 \cos \theta \sin \theta \over g}\] or the equivalent expression:\[ d = {v^2 \sin 2 \theta \over g}\] where \(g = 9.8\) m/s\(^2\), \(\theta\) is the launch angle, and \(v\) is the launch speed.

    1. Using a launch angle of 60\(^\circ\) and a launch speed of \(40\) m/s, verify that both expressions above give the same result for the range.
    2. Now pick one of the equations above and use trial and error to determine the angle that gives maximum range.
v = 40
g = 9.8
  1. (Rydberg’s constant) Rydberg’s constant (\(R_\infty\)) is a physical constant in Rydberg’s formula which was used to predict the spectrum of light emitted by a heavy atom. Rydberg’s constant is given by: \[R_\infty = {m_e e^4 \over 8 \epsilon_0^2 h^3 c}\]
    where
    • \(m_e = 9.109 \times 10^{-31}\) kg is the mass of an electron.
    • \(e = 1.602 \times 10^{-19}\) C is the charge of an electron/proton.
    • \(\epsilon_0 = 8.854 \times 10^{-12}\) C V\(^{-1}\) m\(^{-1}\) is the electrical constant.
    • \(h = 6.626 \times 10^{-34}\) J Hz is the Planck constant.
    • \(c = 3 \times 10^8\) m/s is the speed of light.
    These constants show up all over in physics. In the cell below write some code that assigns the constants to variables and then use the variables to calculate Rydberg’s constant. Use a print statement to display the result. The result should be: \(R_\infty = 10961656.2162\) (in m\(^{-1}\))
# Python Code Here!
  1. In Einstein’s special theory of relativity, the momentum of an object with mass \(m\) (in kg) and velocity \(v\) (in m/s) is given by:\[ p = m v \gamma\] where \[\gamma = {1\over \sqrt{1 - {v^2\over c^2}}}\] with \(c = 3 \times 10^8\) m/s

    1. Calculate the momentum of an object with mass \(m = 0.14\) kg and speed \(v = 50\) m/s. Then compare to the classical expression for momentum: \(p = mv\).
    2. Now calculate the momentum of an object with mass \(m = 0.14\) kg and whose speed is \({1 \over 4}\) the speed of light. Repeat the comparison to the classical value.
    3. Repeat for the following speeds: \({1\over 2}\) the speed of light, \({3\over 4}\) the speed of light, and \({7\over 8}\) the speed of light. Repeat the comparison to the classical value.
# Python Code Here!