= 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. Here is a list of commonly-used functions inside the math module
:
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 Flash Cards
- What are the rules for naming variables in Python?
- When will a mathematical calculation produce a float?
- When will a mathematical calculation produce an int?
- What is the best way to increase/decrease the value of a variable by a multiplicative factor (multiply it by a number)?
- What is the best way to increase/decrease the value of a variable by an additive constant (add a number to it)?
- When assigning large numbers to variables, what character can replace the “,” to separate the numbers into groups of three?
- How do you use scientific notation to assign a very large number to a variable?
- When using a trig function (\(\sin \theta\), \(\cos \theta\), \(\tan \theta\)), the number that is passed in must have what units?
- What does the
math.radians
function do? - Where can you find King Benjamin’s address to his people?
2.4 Exercises
- 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 calledmath
) that will perform this calculation for your. Calculate the distance from the point \((-48,56)\) to the point \((23,81)\) using- Pythogorean’s theorem
- The Python function
hypot
. To learn how to use the hypot function, visit the following documentation page and search for the explanation for thehypot
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!
- 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!
- (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!
(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.
- 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.
- Now pick one of the equations above and use trial and error to determine the angle that gives maximum range.
= 40
v = 9.8 g
- (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.
# Python Code Here!
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
- 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\).
- 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.
- 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!