Lesson 25 +10 XP

Operators Overview

Operators Overview

Operators are symbols that tell Python to do something with values. There are seven main groups.

The groups

GroupExample operatorsJob
Arithmetic+ - / % * //Math
Assignment= += -=Give values
Comparison== != > <Compare values
Logicaland or notCombine booleans
Identityis is notCompare objects
Membershipin not inTest inside a collection
Bitwise& ` ^ ~ << >>`Work on bits

Quick taste

print(5 + 3)      # 8
print(5 == 5)     # True
print("a" in "cat") # True

Operator precedence

When several operators appear, Python follows rules:

  • () first
  • then **
  • then * / // %
  • then + -
  • then comparisons
  • then not
  • then and
  • then or
print(2 + 3 * 4)   # 14 (not 20)
print((2 + 3) * 4) # 20

TL;DR

  • Seven groups of operators exist.
  • Arithmetic does math; comparison and logical drive decisions.
  • Identity (is) compares objects; membership (in) checks collections.
  • * beats +, and parentheses beat everything.