More Math¶
There are lots of ways we can combine numbers or modify them.
>>> count = 5.0
>>> count * 3
15.0
>>> count / 3
1.6666666666666667
>>> count % 3 # remainder
2.0
>>> count // 3 # quotient
1.0
>>> count * 3 + 2
17.0
>>> count * (3 + 2) # parenthesis group
25.0
>>> count / count
1.0
Exponents¶
Exponents are a way of saying “what would happen if I multipled a number X by itself Y times?” So, for instance, what would happen if I multiplied 5 by itself 2 times?
>>> count = 5
>>> count * count
25
>>> count ** 2
25
>>> count * count * count
125
>>> count ** 3
125
this shows up in lots of computation, particularly when we’re trying to figure out how fast a particular operation will be.
Exponents also allow us to answer the question “what number multiplied by itself Y times would give X?” We do that by using a fractional exponent instead of a whole number exponent.
… doctest:
>>> count = 25
>>> count ** (1/2)
5.0
>>> root = count ** (1/2)
>>> root ** 2
25.0
Note
You’ll see count ** (1/2) a lot in your high school math classes, it’s also something you’ll see in geometric programming such as graphics. For instance it lets us figure out how big a square we need to show a given number of pixels. It is normally called a “square root” and is written √25. Cube root **(1/3) is less commonly used.
Exercise¶
Play with numbers, see if you can find an expression that crashes the interpreter
Note
Hint: is there a number that you can’t divide by?
Extra Exercise¶
Note
While this is a fun brain teaser, you won’t use this in this tutorial, bit-wise operators are less commonly used in high-level languages such as Python, but are very common in lower level languages such as C, Go, or Rust.
There are more operators we haven’t seen here.
See if you can figure out what these operators do.
>>> bin(1)
0b1
>>> bin(2)
0b10
>>> 2 >> 1 # called right-shift
1
>>> bin(4)
0b100
>>> 2 << 1 # called left-shift
4
>>> bin(8)
0b1000
>>> 2 << 2
8
>>> 1 & 2 # called bitwise-and
0
>>> 1 & 3
1
>>> 1 ^ 3 # called bitwise-xor
2
>>> ~1 # called bitwise-not
-2
>>> 1|2 # bitwise or
3