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
Example 1Try it yourself
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.

Example 2Try it yourself
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:).

Example 3Try it yourself
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

Example 4Try it yourself
age = 25
print(18 <= age < 65)

Output

True

Test yourself

What does "" or "guest" evaluate to?

  1. ""
  2. "guest"
  3. True
  4. False
Show answer

Answer: "guest"