Python Tutorial · Python Basics · Lesson 12 of 42
Python Operators
Arithmetic, comparison, logical, membership and identity operators.
Operator groups
| Group | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Assignment | = += -= *= /= … |
| Comparison | == != > < >= <= |
| Logical | and or not |
| Membership | in, not in |
| Identity | is, is not |
x = 10
x += 5
print(x)
print(x > 12 and x < 20)
print(not x == 15)
print(3 in [1, 2, 3])
print("z" not in "pizza")
Output
15 True False True False
Logical operators short-circuit
and stops at the first falsy value and or stops at the first truthy value — and they return that value, not just True/False.
print(0 or "default")
print("value" or "default")
print(None and 5)
name = ""
print(name or "Anonymous")
Output
default value None Anonymous
== vs is
== compares values; is checks whether two names point to the same object. Use is only for None (if x is None:).
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)
c = a
print(a is c)
Output
True False True
Chained comparisons
age = 25
print(18 <= age < 65)
Output
True
Test yourself
What does "" or "guest" evaluate to?
"""guest"TrueFalse
Show answer
Answer: "guest"