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...
-17
-17
-1 + 3.14
2.14
2 ** 3
8
(17 - 14) / 2
1.5
15 % 2
1
60 / 2 * 3 # Evaluates to 90.0 (this is a comment)
90.0
60 / (2 * 3) # Evalutes to 60.0
10.0
60 / (2 * 4) # Evaluates to 7.5
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.
2 + 3 # Computes 2 + 3
5
Here's an example of a better comment.
# Finds the largest multiple of 17 less than 244
17 * (244 // 17)
238
We glossed over something earlier – it seems like there are two different types of numbers!
2 + 3
5
10 / 2
5.0
You can get the type of a value by calling the type
function. We will learn more about functions later.
type(5)
int
type(5.0)
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.
3 + (2**9) - 15 * 14 + 1
306
3 + (2**9) - 15 * 14 + 1.0
306.0
# Notice how the result is a float, even though 3 divides 15 evenly!
15 / 3
5.0
Weird things can happen when performing arithmetic with floats.
# Should be 0.6
0.1 + 0.2 + 0.3
0.6000000000000001
# Should be 0.2
0.1 + 0.1
0.2
# Should be 1.4
0.1 + 0.1 + 0.1 + 1 + 0.1
1.4000000000000001
What happens if we try dividing by 0?
5 / 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) /tmp/ipykernel_23/2219314525.py in <module> ----> 1 5 / 0 ZeroDivisionError: division by zero
# In math classes you may have learned that this value is undefined, but I guess Python chose it to be 1
0 ** 0
1
You'll also get an error if your code is syntactically wrong.
2 +
File "/tmp/ipykernel_23/4087983127.py", line 1 2 + ^ SyntaxError: invalid syntax
3 ** / 4
File "/tmp/ipykernel_23/4045155691.py", line 1 3 ** / 4 ^ SyntaxError: invalid syntax