Pre-MAP Course Website | Pre-MAP GitHub | Google
Math in Python works like most scientific calcators, but Python can do a lot more than your calculator. In this lesson, we'll do some math.
You can type some basic math in a cell, execute the cell (Ctrl + Enter
), and math will be returned below the cell. This works whether or not you put the math in a print
command. Try 2+2
in the cell below:
In [ ]:
The symbol for multiplication is *
. Do 2 * 2
below:
In [ ]:
In [ ]:
If you want to represent a large number with scientific notation, you can do that with a small e
, like this:
two_times_ten_to_the_fifth = 2e5
where the above is $2 \times 10^5$.
Types can fool you sometimes when you're dividing two numbers. If you divide with one division sign (/
) you will get a float
result, which is the way Python represents decimals. If you divide with two division signs (//
) you will always get an integer result.
Try dividing three by five using /
, and then with //
. What's the difference? What is the type
of each result?
In [ ]:
Exponentiation uses two asterisks **
(not the caret symbol ^
), like this:
print(2**2)
If you already have a variable, you can add, subtract, multiply, divide onto that existing variable in two ways. One is like this:
class_number = 192
class_number = class_number + 1
or
class_number = 192
class_number += 1
The number of great-great-great... grandparents you have goes as $2^n$ where $n$ is the number of generations back you go. For example, one generation ago $n=1$, you had $2^1 = 2$ ancestors - or two parents. Two generations ago, you had $2^2 = 4$ ancestors - or four grandparents.
Use Python to answer: how many ancestors did you have thirty generations ago?
In [ ]:
If that number sounds way larger than the number of people that were probably on Earth thirty generations ago, that's because it is. How is that possible? You can read up more about this after class by following this link.
You can also use Python to compute inequalities. The operators used in inequalities are:
Inequality | Symbol |
---|---|
Equal to | == |
Not equal to | != |
Greater than | > |
Greater than or equal to | >= |
Less than | < |
Less than or equal to | <= |
Note: you can check if something is equal to something else with the double equals ==
. You can't use single equals, because that's how you define a variable. So this sets the variable x
to the value 5
:
x = 5
while this asks if x
is equal to 5:
x == 5
What is returned when you evaluate an inequality like 3 >= 5
? What is the type of this object?
In [ ]:
Another operator that's useful is the modulus operator, represented with the symbol %
. The modulus of two numbers is the remainder after dividing the first number by the second. So for example, 4 % 2
is zero, because four divided by two is 2 with no remainder. But 9 % 4
is one, because nine goes into four two times with one leftover.
This gets used sometimes to search for multiples, since if x
is a multiple of three, then $x \,\% \,3 = 0$.
In the cell below, determine whether or not 12417 is an even multiple of three:
In [ ]:
So far we've been writing only a few lines of code at a time in each cell, but soon you'll be writing lots of lines. The more code you write, the harder it can be to remember what each step was. That's why we write lots of comments in our code.
A comment is a note you wrote in code, which Python doesn't do anything with. It's just text for human readers. You designate a comment with a #
symbol - anything after the #
gets ignored by Python. For example:
# Here, I'm going to calculate the force on a 10kg block:
mass = 10 # kilograms
acceleration = 5 # meters per sec^2
force = mass * acceleration # I <3 Newton
print(force)
If the price of the computer you're working on was $1000 and the sales tax in Seattle is 9.6%, how much did it cost after tax?
Do this calculation by creating variables for the tax rate, the price of the computer before tax, and the final price, and leave comments throughout explaining the units and the calculation that you're doing. See the example above for hints.
In [ ]:
In Python, you have to be careful about putting spaces or tabs in front of a line. We call spaces and/or tabs collectively whitespace.
You can put as many spaces as you want in a line (though one at a time is the right number to use most of the time), like this:
this_is_ok = 2 + 2
this_is_bad_but_it_works = 2 + 2+2
However you can't put stray spaces in the beginning of a line. For example, if you do this:
starts_no_indent = 0
starts_with_an_indent = 5
...an error will be raised.
Try the above example or one like it, and note the type of error that it raises:
In [ ]:
It will become clear later why this isn't allowed - indentation is used to represent specific things.
When you start your research project, you'll write code that you'll use for the rest of the quarter. If you can't read your own code, then you'll have difficulty understanding what you did at the end of the quarter. Readability is really important for making your work understandable and reproducible. Just like you wouldn't turn in your scratch paper version of your math homework, you shouldn't allow yourself to write illegible code.
As scientists, we share our work with one another and review each other's answers. Ask your neighbor to look at your solution to Example 5. Ask your neighbor:
Here are some tips on naming variables to remember:
There are lots more tips about how to write Python code "correctly" in the style guide, often called "PEP8", which I'll leave a link to here for future reference.
Can you improve your variarble names and style in Example 5? If so, get to it!
You can now use Python as a calculator, but it's more useful than a handheld calculator only when you have lots of numbers to work with. You can store a group of numbers, or groups of other things, in a type called a list
.
A list is a collection of things (they can have any type, including int
s, float
s, str
s. They are separated by commas and bracketed with square brackets ([
and ]
), like this:
shopping_list = ['apple', 'banana', 'cherry']
Ask a few neighbors around you for their ages, create a list of their ages, and print the list:
In [ ]:
Many times you'll want to check how many elements are in your list, which you do with the len
function, like this:
len(ages)
Try that in the cell below:
In [ ]:
Python has a function for taking the sum
of the numbers in a list. Let's take the sum of the ages with the following command:
sum(ages)
What is the cumulative number of years your neighbors have been alive (take the sum of the ages)? Store the answer in a variable with a sensible name (remember guidelines from above!), and print the result:
In [ ]:
Often you'll want to be able to take a single element, or a few elements out of a list. To do that, you do what we call indexing or slicing.
To get a specific element from of the list ages
, we put square brackets next to the name of the list, and we put the index of the element that we want inside the brackets. The index starts at zero for the first element, one for the second element, etc.:
first_element = ages[0]
print(first_element)
Get the second element out of the list ages
. Double check that you got the right element.
In [ ]:
If you want to get out multiple elements at a time, you can use two indices which designate the start and stop+1 indices, separated by a :
symbol. For example, let's get the fourth through seventh letters in this list:
# Index = 0 1 2 3 4 5 6 7 8 9
astr192 = ['P', 'r', 'e', 'M', 'A', 'P', '2', '0', '1', '6']
print(astr192[3:8])
which prints ['M', 'A', 'P', '2', '0']
. The fourth element is at index 3, so that's the first number in the slice. The second number in the slice is the stop position plus one.
full_name
name = "Pre-MAP"
name_list = list(name)
print(name_list)
['P', 'r', 'e', '-', 'M', 'A', 'P']
. Do this to make a list out of your name.
In [ ]:
You can get all elements starting with the third element by doing name_list[2:]
, and you can get all elements up to the third by doing name_list[:3]
. Give it a try below:
In [ ]:
This will be useful when you have long lists of numbers in the near future.
Let's say someone new transferred into the class, and you want to add their age to the ages
list. We can do that with the append
function, which you call like this:
new_age = 20
ages.append(new_age)
print(ages)
In the second line, ages
is the list that we're appending a new number to, .append()
says to append the number in parentheses onto ages
.
Copy and paste the code above into the cell below and execute the cell once, to see the output.
In [ ]:
In [ ]: