Operators in Python are all about manipulating data. The most common operator types are:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
Arithmetic operators
Arithmetic operators are used to carry out common mathematical operations.
| Arithmetic operator | Meaning |
| a + b | Adds the value of b to a |
| a – b | Subtracts the value of b from a |
| a * b | Multiplies a by b |
| a / b | Divides a by b |
| a ** b | Raises a to the power of b |
| a % b | Divides a by b and returns the remainder |
| a // b | Divides a by b and rounds down |
Assignment Operators
Assignment operators are a shortcut that combine an arithmetic operator and then assign the outcome of that equation to a variable. For example:
total_number_of_days += days_this_week
Is the same as typing:
total_number_of_days = total_number_of_days + days_this_week
| Assignment operators | Meaning |
| a += b | a = a + b |
| a -= b | a = a -b |
| a *= b | a = a * b |
| a /= b | a = a/ b |
| a **= b | a = a ** b |
| a //= b | a = a // b |
Comparison Operators
Comparison Operators compare two variables or statements and return a Boolean True or False.
| Comparison Operators | Meaning |
| a == b | True if a is equal to b |
| a != b | True if a is not equal to b |
| a < b | True if a is less than b |
| a > b | True if a is greater than b |
| a <= b | True if a is less than or equal to b |
| a >= b | True if a is greater than or equal to b |
Logical Operators
Logical Operators are used to combine statements and return a Boolean True or False based on the result.
| Logical operator | Meaning |
| a or b | True if either a or b is True |
| a and b | True only if both a and b are True |
| not a | True if a is False |
Precedence
Precedence determines the order in which operations are carried out. An operation with a higher precedence will be calculated before a lower one.
| Highest Precedence | Operator | Symbol |
| Parentheses | () | |
| Exponential | ** | |
| Multiplication, division, modulo, and floor division | *, /, %, // | |
| Addition and subtraction | +, – | |
| Comparison operators | <, >, <=, >= | |
| Equality operators | ==, != | |
| Assignment operators | =, +=, -=, *=, /=, %=, //=, **= | |
| Lowest precedence | Logical operators | or, and, not |
If in any doubt, wrap the separate parts in brackets so that each operation is unaffected by the others.
total = ((a + b) – (x * y)) / z
