Python Operators
An operator is a symbol that works on values: + adds, == compares, and combines. You have met several already. This topic collects them in groups and explains the order in which Python applies them when an expression has more than one.
Arithmetic and assignment
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 7 * 3 | 21 |
/ | divide | 7 / 2 | 3.5 |
// | divide and round down | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | power | 2 ** 5 | 32 |
Every arithmetic operator has an assignment form that changes a variable in place: x += 3 is x = x + 3, and likewise -=, *=, /=, //=, %= and **=.
Comparison and logic
==, !=, <, >, <= and >= compare two values and give a boolean; and, or and not combine booleans. The Booleans topic explains them in detail.
Membership and identity
in and not in check whether a value is part of a collection or of a string. is and is not check whether two names refer to the same object, which is different from having equal values:
fruits = ["apple", "mango"]
print("mango" in fruits, "kiwi" not in fruits)
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
value = None
print(value is None)True True True False True True
a and b are equal lists but two separate objects; c is another name for the very same list as a. Use == to compare values, and keep is for checking None.
Bitwise operators
&, |, ^, ~, << and >> work on the binary digits of whole numbers. They are used for flags and low-level data: 6 & 3 is 2, 6 | 3 is 7, and 1 << 4 is 16. You will rarely need them while learning.
Order of precedence
When an expression has several operators, Python applies them in a fixed order: ** first, then *, /, // and %, then + and -, then comparisons, then not, and and or. Brackets always come first, so use them whenever the order is not obvious:
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-3 ** 2, (-3) ** 2)14 20 512 -9 9
** is the one operator that groups from the right: 2 ** 3 ** 2 is 2 ** 9. It also binds tighter than a minus sign in front, so -3 ** 2 is -(3 ** 2).
Practice exercises
- Start with
n = 7and use assignment operators to make it 7 times larger, then subtract 9, then halve it with//. - Check with
inwhether the letter"y"is in"Python"and in"Java". - Work out
100 - 5 * 3 ** 2by hand, then check it in the interpreter. - Create two equal lists and show that
==isTruebutisisFalse.