beginner Step 3 of 20

Operators and Expressions

Python Programming

Operators and Expressions

Operators are special symbols or keywords that perform operations on values and variables. An expression is a combination of values, variables, and operators that Python evaluates to produce a result. Understanding operators is essential because they form the basis of all computations in your programs — from simple arithmetic to complex logical conditions that control program flow. Python provides a rich set of operators organized into several categories.

Arithmetic Operators

Arithmetic operators perform mathematical calculations. Python supports all standard math operations plus a few extras like integer division and exponentiation that many other languages lack as built-in operators.

# Basic arithmetic
a, b = 17, 5

print(a + b)   # 22  — Addition
print(a - b)   # 12  — Subtraction
print(a * b)   # 85  — Multiplication
print(a / b)   # 3.4 — Division (always returns float)
print(a // b)  # 3   — Floor division (rounds down)
print(a % b)   # 2   — Modulo (remainder)
print(a ** b)  # 1419857 — Exponentiation (17^5)

# Order of operations (PEMDAS)
result = 2 + 3 * 4      # 14, not 20
result = (2 + 3) * 4    # 20, parentheses first

# Negative floor division rounds toward negative infinity
print(-17 // 5)   # -4 (not -3!)
print(-17 % 5)    # 3

Comparison Operators

Comparison operators compare two values and return a boolean (True or False). These are fundamental for conditional statements and loops.

x, y = 10, 20

print(x == y)   # False — Equal to
print(x != y)   # True  — Not equal to
print(x > y)    # False — Greater than
print(x < y)    # True  — Less than
print(x >= 10)  # True  — Greater than or equal
print(x <= 5)   # False — Less than or equal

# Chained comparisons (unique to Python)
age = 25
print(18 <= age <= 65)  # True — checks both conditions

# Comparing strings (lexicographic order)
print("apple" < "banana")  # True
print("abc" == "abc")      # True

Logical Operators

Logical operators combine boolean expressions. Python uses the English words and, or, and not instead of symbols like &&, ||, and ! used in other languages.

a, b = True, False

print(a and b)   # False — both must be True
print(a or b)    # True  — at least one must be True
print(not a)     # False — inverts the value

# Practical example
age = 25
has_license = True
can_drive = age >= 16 and has_license
print(can_drive)  # True

# Short-circuit evaluation
# Python stops evaluating as soon as the result is determined
x = 0
result = x != 0 and 10 / x > 2  # 10/x never executes (avoids ZeroDivisionError)

# Truthy/Falsy with logical operators
name = "" or "Default"     # "Default" (empty string is falsy)
value = None or 42         # 42
config = {"key": "val"} or {}  # {"key": "val"}

Assignment Operators

Assignment operators combine an arithmetic operation with assignment, providing a shorthand for common update patterns.

x = 10

x += 5    # x = x + 5  → 15
x -= 3    # x = x - 3  → 12
x *= 2    # x = x * 2  → 24
x /= 4    # x = x / 4  → 6.0
x //= 2   # x = x // 2 → 3.0
x **= 3   # x = x ** 3 → 27.0
x %= 5    # x = x % 5  → 2.0

# Works with strings too
greeting = "Hello"
greeting += " World"  # "Hello World"

# And lists
numbers = [1, 2]
numbers += [3, 4]     # [1, 2, 3, 4]

Identity and Membership Operators

Python provides is / is not to check object identity (whether two variables point to the same object in memory) and in / not in to check membership in a collection.

# Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True  — same values
print(a is b)    # False — different objects in memory
print(a is c)    # True  — same object

# Always use 'is' to compare with None
value = None
if value is None:
    print("No value set")

# Membership operators
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)      # True
print("grape" not in fruits)   # True

# Works with strings
print("Py" in "Python")       # True

# Works with dictionaries (checks keys)
config = {"host": "localhost", "port": 8080}
print("host" in config)       # True
print(8080 in config)         # False (checks keys, not values)
Pro tip: Use is only for identity checks (especially None, True, False) and == for value equality. Using is to compare integers or strings can give unexpected results due to Python's object caching behavior.

Key Takeaways

  • Python supports arithmetic (+, -, *, /, //, %, **), comparison (==, !=, <, >, <=, >=), and logical (and, or, not) operators.
  • Division (/) always returns a float; use floor division (//) for integer results.
  • Python supports chained comparisons like 1 < x < 10 which is unique and very readable.
  • Use is for identity checks (especially with None) and == for value equality.
  • The in operator checks membership in sequences, strings, and dictionary keys.