ℹ

# Mathematical Statements

Let's do some MATH!

We will start simple, with some mathematical expressions all of you should be familiar with. Let's mess around with them first before we start analyzing what Python is doing behind the scenes.

>>> a, b = 4, 8

>>> b + a

12

>>> b - a

4

>>> b * a

32

I'll take a moment to talk about three operators that are closely related to each other — division, floor division, and multiplication.

Division in Python always returns a decimal — known in computer-speak as a "float".

>>> a, b = 4, 8

>>> b / a

2.0

>>> c, d = 6, 4

>>> c / d

1.5

To get an integer result from division, we can use the floor division operator (

`//`

), which divides by discarding the decimal section entirely (or rounding down, if that's easier for you to visualize).>>> a, b = 4, 8

>>> b // a

2

>>> c, d = 6, 4

>>> c // d

1

A complimentary operator to the floor division operator is the modulo operator (

`%`

), which returns the remainder derived from the division.>>> a, b = 4, 8

>>> b % a

0

>>> c, d = 6, 4

>>> c % d

2

These are operations some of you may never have seen before! I'd recommend playing around with them to get a feel for both they work. Here's some things to try out:

>>> a, b = 4, 8

>>> a % b

???

>>> c, d = -1, 6

>>> c % d

???

Find out what these values return! The negative modulo is most definitely out of scope, but if you're curious, here's an interesting article about it.

You might be curious about the order in which Python executes statements like the ones we've talked about above. We did so intuitively, but it is important to realize that Python does not have an "intuitive" setting. Let's attempt to understand how Python evaluates these expressions.

>>> a, b = 4, 8

>>> a + b

First, the operator is evaluated — Python figures out what the

`+`

sign means. Then, it figures out what `a`

is — here, it is 4. Then it figures out what `b`

is — here, that is 8. Finally, it executes that expression with the evaluated values — `4 + 8 = 12`

. One last note: Python follows PEMDAS, which I'll assume you're familiar with. As a closing challenge, try to figure out the process through which Python evaluates the following:

>>> (3 + 4) % 5 + 7 // 8

Last modified 1yr ago