This is part of “An intro to Python” series of posts, with content from the Enki app. If you stumbled upon this, you can start from the beginning.
Similar to other programming languages, Python uses standard arithmetic operators.
The four standard operators are +, -, * and /. These allow us to add, subtract, mutiply and divide.
Here they are in use:
In Python 3, using the division operator / will always return a float. And whenever you use a float in your calculation, a float will be returned, even if the number is a whole number ending in .0.
If you want to perform floor division to return an int, use the // operator:
When using the // operator, you only return the whole number part of the division. Any digits after the decimal point will be removed.
Python uses the exponent operator, **, to multiply a number to the power of another.
This code executes 2 to the power of 4.
Here are some other examples:
Note how the ** operator is executed before the - in the first example, so the calculation is -(3**4). More about this order of execution in the next section!
Python uses the modulus operator, %, to return the remainder of a division.
14 divided by 3 equals 4 remainder 2. The modulus operator returns this remainder 2.
When using more than one operator in Python, it’s crucial to understand the order they’ll be executed in.
What will be the result of the following expression?
Here is the order of execution for Python’s operators (highest to lowest):
In Python we’re able to chain operators. This means that we can use more than one at a time, like this:
Chaining operators is equivalent to: