Pre-MAP Course Website | Pre-MAP GitHub | Google

Python as a calculator

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.

Example 1: Math in a cell

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 [ ]:

The numbers we've used so far are all integers, or int's. Python can store numbers as ints or floats. A float is a decimal number. You can check what type a number is by using the type function:

type(5)

Example 2: Types

Print the types of the following things:

  • 1
  • 1.0
  • "hello, world"

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.

Example 2: Integer vs. float division

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)

Inplace addition

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

Example 3: How many ancestors do you have?

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

Example 4: Inequalities, booleans

What is returned when you evaluate an inequality like 3 >= 5? What is the type of this object?


In [ ]:

Example 5: Other operators

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 [ ]:


Comments

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)

Example 5: Comments welcome

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.

Example 6: Significant whitespace

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.


Style

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:

  • Can you figure out what I was trying to accomplish with my code?
  • Do my variable names make sense to you?
  • Did I use appropriate whitespace to make the code easy to read?
  • Did I write enough comments to guide you through what I was doing?

Here are some tips on naming variables to remember:

  • Variable names should use lowercase letters and numbers
  • If there's more than one word in your variable name, separate the words with underscores
  • Longer names are better than shorter names! No one ever got mad that someone else's code was too readable

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.

Example 7: Variable names

Can you improve your variarble names and style in Example 5? If so, get to it!


Lists

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 ints, floats, strs. 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)

Example 8: Sum of a list

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 [ ]:

List indexing and slicing

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)

Example 9: Zero-based indexing

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.

Example 10: List slicing

  1. Type your full name in a string, store it in the variable full_name
  2. You can turn that string into a list of strings by doing this:
    name = "Pre-MAP"
    name_list = list(name)
    print(name_list)
    
    which yields ['P', 'r', 'e', '-', 'M', 'A', 'P']. Do this to make a list out of your name.
  3. Get the second through seventh letters in your name with slicing.

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.


Adding items to a list

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 [ ]:

Example 11:

What would happen if you executed the cell above a second time? Try it and check your answer.


In [ ]: