Python Operators
Operators are the symbols Python uses to perform calculations, compare values, and combine conditions.
What is an operator?
An operator is a special symbol or keyword that tells Python to carry out an action on one or more values. The values an operator acts on are called operands. For example, in the expression 3 + 4, the plus sign is the operator while 3 and 4 are the operands. Almost every useful program is built from expressions like this, so getting comfortable with operators is one of the first real steps toward writing Python.
Python groups its operators into several families depending on what kind of work they do. You will meet each family in detail on the following pages, but it helps to see the whole landscape first so you understand how the pieces fit together.
- Arithmetic operators perform math such as addition, subtraction, and division.
- Comparison operators check how two values relate and return True or False.
- Logical operators combine or invert boolean expressions using and, or, and not.
- Assignment operators store a value in a variable, sometimes updating it in place.
- Identity operators (is, is not) check whether two names point to the same object.
- Membership operators (in, not in) check whether a value appears inside a sequence.
A quick tour of the main families
total = 10 + 5 # arithmetic
print(total) # 15
print(total > 12) # comparison -> True
is_valid = total > 12 and total < 20 # logical
print(is_valid) # True
colors = ["red", "green"]
print("red" in colors) # membership -> TrueWhen several operators appear in one expression, Python decides the order of evaluation using precedence rules, similar to the order of operations you learned in math class. Multiplication and division happen before addition and subtraction, and you can always use parentheses to make the order explicit and easier to read.
Precedence and parentheses
print(2 + 3 * 4) # 14, because * runs before +
print((2 + 3) * 4) # 20, parentheses force + first
print(10 - 2 - 3) # 5, same-level operators run left to rightExercise: Python Operators
What does the // operator do in Python?