βΉοΈMathematical Statements
Let's do some MATH!
Introduction to Operators
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.
Division, Floor Division and Modulo
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".
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 complimentary operator to the floor division operator is the modulo operator (%
), which returns the remainder derived from the division.
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:
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.
How Python Reads Mathematical Statements
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.
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:
Last updated