Aller au contenu principal

01.2 - Operators & Expressions

Theory 20 min Beginner

What is an Operator?

An operator is a symbol that tells Python to perform a specific operation on one or more operands.

result = 10 + 5   # `+` is the operator, 10 and 5 are operands

Python has 7 categories of operators:


1. Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/True division10 / 33.333...
//Floor division10 // 33
%Modulo10 % 31
**Exponentiation2 ** 8256
# Division nuances
10 / 4 # 2.5 (always float)
10 // 4 # 2 (floor: rounds down)
-10 // 4 # -3 (floor of -2.5 is -3!)
10 % 4 # 2 (remainder)

# Common use of modulo
def is_even(n):
return n % 2 == 0

# String and list operators
"hello" + " world" # "hello world" (concatenation)
"ab" * 3 # "ababab" (repetition)
[1, 2] + [3, 4] # [1, 2, 3, 4]

2. Comparison Operators

Comparison operators return True or False.

OperatorMeaningExampleResult
==Equal5 == 5True
!=Not equal5 != 3True
<Less than3 < 5True
>Greater than5 > 3True
<=Less or equal5 <= 5True
>=Greater or equal6 >= 5True
# Python allows chaining comparisons!
1 < 2 < 3 # True (equivalent to 1 < 2 and 2 < 3)
1 < 2 > 0 # True
10 <= 10 < 20 # True

# Warning: == vs is
a = [1, 2, 3]
b = [1, 2, 3]
a == b # True (same content)
a is b # False (different objects in memory)

x = None
x == None # True (works but not recommended)
x is None # True (preferred — checks identity)

3. Logical Operators

OperatorMeaningExample
andBoth must be TrueTrue and FalseFalse
orAt least one TrueTrue or FalseTrue
notNegationnot TrueFalse
age = 25
has_id = True

# Both conditions
if age >= 18 and has_id:
print("Access granted")

# Either condition
if age < 13 or age > 65:
print("Special pricing")

# Negation
if not has_id:
print("Show your ID")

Short-Circuit Evaluation

Python evaluates logical expressions lazily:

  • and: stops at first False
  • or: stops at first True
# Short-circuit: safe division — division only evaluates if x != 0
x = 0
result = x != 0 and 10 / x # False — division never executed!

# Short-circuit with or: default value pattern
name = user_input or "Anonymous"
# If user_input is "" or None, name = "Anonymous"

4. Assignment Operators

OperatorExampleEquivalent
=x = 5Assign 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 2x = x * 2
/=x /= 2x = x / 2
//=x //= 2x = x // 2
**=x **= 2x = x ** 2
%=x %= 3x = x % 3
score = 100
score += 10 # 110
score -= 5 # 105
score *= 2 # 210

# Walrus operator (Python 3.8+): assign and test simultaneously
import re
if match := re.search(r"\d+", "abc123"):
print(match.group()) # "123"

5. Identity Operators (is, is not)

OperatorMeaning
isSame object in memory
is notDifferent objects in memory
a = None
b = None

a is None # True (always use `is` with None)
a is not None # False

# Integer caching: Python caches small integers (-5 to 256)
x = 100
y = 100
x is y # True (cached)

x = 1000
y = 1000
x is y # False (not cached)
x == y # True (same value)

6. Membership Operators (in, not in)

OperatorMeaning
inElement exists in a sequence
not inElement does not exist
fruits = ["apple", "banana", "cherry"]
"banana" in fruits # True
"mango" not in fruits # True

# Works on strings
"py" in "python" # True
"z" not in "hello" # True

# Works on dicts (checks keys)
data = {"name": "Alice", "age": 30}
"name" in data # True
"email" in data # False

Operator Precedence (PEMDAS)

When multiple operators appear, Python follows this precedence (high to low):

PriorityOperatorDescription
1 (highest)()Parentheses
2**Exponentiation
3+x, -x, ~xUnary operators
4*, /, //, %Multiplication & division
5+, -Addition & subtraction
6<<, >>Bitwise shifts
7&Bitwise AND
8^Bitwise XOR
9|Bitwise OR
10==, !=, <, >, etc.Comparisons
11notLogical NOT
12andLogical AND
13 (lowest)orLogical OR
# Without parentheses — can be confusing
2 + 3 * 4 # 14 (not 20! * before +)
2 ** 3 ** 2 # 512 (right-associative: 2 ** 9)

# With parentheses — always clear
(2 + 3) * 4 # 20
not True or True # True (not True = False, then False or True = True)
not (True or True) # False (True or True = True, then not True = False)

Rule: When in doubt, use parentheses. Clarity beats cleverness.


Key Vocabulary

TermDefinition
OperatorA symbol performing an operation (+, ==, and)
OperandThe values on which an operator acts
ExpressionCombination of values, variables, and operators that evaluates to a result
Floor division// — divides and rounds down to nearest integer
Modulo% — returns the remainder of a division
Short-circuitLogical operators stop evaluating when the result is determined
Walrus operator:= — assigns and returns a value in one expression (Python 3.8+)
Operator precedenceRules determining the order in which operators are evaluated

Summary

  • Python has 7 operator categories: arithmetic, comparison, logical, assignment, identity, membership, bitwise
  • / always returns float; use // for integer division
  • Use is / is not for identity checks (especially is None)
  • Use in / not in for membership tests in lists, strings, dicts
  • and and or use short-circuit evaluation — useful for defaults and guards
  • When precedence is unclear, add parentheses to make intent explicit