# Lecture 2 – Jupyter Notebooks and Arithmetic¶

## Data 94, Spring 2021¶

In each of the following cells, there is an expression. After running each cell, you see the value of that expression.

In general, Jupyter notebook cells show you the value of the very last expression in a cell. But generally we'll want to do more than one computation in a cell. In the next lecture, we'll learn how to store our calculations in variables. But for now...

In [1]:
-17

Out[1]:
-17
In [2]:
-1 + 3.14

Out[2]:
2.14
In [3]:
2 ** 3

Out[3]:
8
In [4]:
(17 - 14) / 2

Out[4]:
1.5
In [5]:
15 % 2

Out[5]:
1
In [6]:
60 / 2 * 3 # Evaluates to 90.0 (this is a comment)

Out[6]:
90.0
In [7]:
60 / (2 * 3) # Evalutes to 60.0

Out[7]:
10.0
In [8]:
60 / (2 * 4) # Evaluates to 7.5

Out[8]:
7.5

This is a Markdown cell! You can change the type of a cell by going to the cell toolbar.

Here's an example of a useless comment.

In [9]:
2 + 3 # Computes 2 + 3

Out[9]:
5

Here's an example of a better comment.

In [10]:
# Finds the largest multiple of 17 less than 244
17 * (244 // 17)

Out[10]:
238

## Variable Types¶

We glossed over something earlier – it seems like there are two different types of numbers!

In [11]:
2 + 3

Out[11]:
5
In [12]:
10 / 2

Out[12]:
5.0

You can get the type of a value by calling the type function. We will learn more about functions later.

In [13]:
type(5)

Out[13]:
int
In [14]:
type(5.0)

Out[14]:
float

Any time you add, subtract, or multiply any number of ints, the result is still an int. But anytime you divide, or use a float in a calculation, the result is a float.

In [15]:
3 + (2**9) - 15 * 14 + 1

Out[15]:
306
In [16]:
3 + (2**9) - 15 * 14 + 1.0

Out[16]:
306.0
In [17]:
# Notice how the result is a float, even though 3 divides 15 evenly!
15 / 3

Out[17]:
5.0

Weird things can happen when performing arithmetic with floats.

In [18]:
# Should be 0.6
0.1 + 0.2 + 0.3

Out[18]:
0.6000000000000001
In [19]:
# Should be 0.2
0.1 + 0.1

Out[19]:
0.2
In [20]:
# Should be 1.4
0.1 + 0.1 + 0.1 + 1 + 0.1

Out[20]:
1.4000000000000001

## Errors¶

What happens if we try dividing by 0?

In [21]:
5 / 0

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
----> 1 5 / 0

ZeroDivisionError: division by zero
In [22]:
# In math classes you may have learned that this value is undefined, but I guess Python chose it to be 1
0 ** 0

Out[22]:
1

You'll also get an error if your code is syntactically wrong.

In [23]:
2 +

  File "<ipython-input-23-1a637eb9c307>", line 1
2 +
^
SyntaxError: invalid syntax

In [24]:
3 ** / 4

  File "<ipython-input-24-06fb607b1414>", line 1
3 ** / 4
^
SyntaxError: invalid syntax