Math and Numbers

Lesson 5

Python has a simple and straight forward approach to programming math and numbers—if you are OK with high school math, you will be OK with Python math.

Carrying on from earlier examples, here are a few more using the Python interactive interpreter (don’t type in the comments, I have added them for your information only):

```
>>> 50 - 5*6 # Mathematical precedence
20 # PEMDAS, BEDMAS or BODMAS
>>> (50 - 5) * 6 # depending which country you're from
270
>>> 2**10 # Power functions
1024
>>> import math # Python math module
>>> r = 10
>>> area = math.pi*(r**2) # Using pi
>>> area
314.1592653589793
>>> math.cos(math.radians(60)) # Trigonometry
0.5000000000000001
>>> math.log(256,2) # logarithms
8.0
>>> import random # Python random module
>>> random.random()
0.5362880665009504
>>> random.randrange(12)
11
>>> random.randrange(12)
4
>>>
```

Here’s a screenshot of the complete exercise:

There are dozens more functions you can use to do math and manipulate numbers in Python. For a list of all math functions, check out the Python documentation.