x = 3
y = (x**2 +x) / 2*x
print(f"f({x})= {y}")f(3)= 18.0
Like PEDMAS for math equations (‘Parenthesis’, ‘Exponents’, ‘Division/Multiplication’, ‘Addition/Subtraction’), there is an order of operations for resolving programming operations (assignment, comparison, arithemetic and logical)
Order of Operations, from highest to lowest
| Operation | Order | Example | Explanation |
|---|---|---|---|
() |
1 | (x + y) * z |
grouping expressions to force them to be evaluated first |
** |
2 | 2 ** 3 |
exponentiation (raising one value to the power of another) |
*, /, //, % |
3 | x * y |
multiplication, division, floor division, and remainder (modulo) |
+, - |
4 | x + y |
addition and subtraction |
in, not in * |
5 | 'hi' in greetings |
is something in, or not in, a list (or list-like object) (returns Boolean) |
<, <=, >, >=, !=, == |
5 | x < y |
comparison of two things (returns Boolean) |
not |
6 | not x |
negating the True/False value of x (returns Boolean) |
and |
7 | x < y and x > z |
combining two Boolean values (returns Boolean) |
or |
8 | x < y or x > z |
combining two Boolean values (returns Boolean) |
=, +=, -=, *=, /=, //=, %=**= |
9 | x += 1 |
assigning or updating the value of a variable |
in
This is called the membership operator and checks if an element is found in a structure of elements. For example is “c” found in “cocoa”. We will see it a little bit later in the course.
These sets of equations are equivalent (assume all variables are boolean):
Consider the following math function \(y = \frac{x^2 + x}{2x}\) implemented in Python as such:
This isn’t the correct value of \(f(3)\), which should be \(2\). Why is that?
The answer lies in how the denominator has been implemented /2*x. This is ambigious because both the / and the * have the same priority. Python doesn’t know that 2*x must be computed first, following by the division. By default, Python reads and executes expressions from left to right, performing the division first and then the mulitplication.
To remove the ambiguity, the best is to use parenthesis ():
Adding more parenthesis than necessary is always better than not enough! When writing complex expressions, use as many parentheses as needed to make the order of operations clear.