# 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 :
-17

Out:
-17
In :
-1 + 3.14

Out:
2.14
In :
2 ** 3

Out:
8
In :
(17 - 14) / 2

Out:
1.5
In :
15 % 2

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

Out:
90.0
In :
60 / (2 * 3) # Evalutes to 60.0

Out:
10.0
In :
60 / (2 * 4) # Evaluates to 7.5

Out:
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 :
2 + 3 # Computes 2 + 3

Out:
5

Here's an example of a better comment.

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

Out:
238

## Variable Types¶

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

In :
2 + 3

Out:
5
In :
10 / 2

Out:
5.0

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

In :
type(5)

Out:
int
In :
type(5.0)

Out:
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 :
3 + (2**9) - 15 * 14 + 1

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

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

Out:
5.0

Weird things can happen when performing arithmetic with floats.

In :
# Should be 0.6
0.1 + 0.2 + 0.3

Out:
0.6000000000000001
In :
# Should be 0.2
0.1 + 0.1

Out:
0.2
In :
# Should be 1.4
0.1 + 0.1 + 0.1 + 1 + 0.1

Out:
1.4000000000000001

## Errors¶

What happens if we try dividing by 0?

In :
5 / 0

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

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

Out:
1

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

In :
2 +

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

In :
3 ** / 4

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