Language:

Search

Python Operators Expressions — Arithmetic, Comparison, Logical, Assignment, Membership Identity

In this lesson, you’ll learn how to combine values into expressions using Python’s operators. We’ll cover arithmetic, comparison, logical, assignment, membership, and identity operators, with clear, practical examples.


0) Expressions & Precedence (Quick Intro)

An expression is any piece of code that produces a value. Python evaluates operators by precedence (order of operations). Use parentheses (...) to make your intent clear.


result = 2 + 3 * 4     # 2 + (3*4) = 14
result = (2 + 3) * 4   # (2+3)*4 = 20
  

1) Arithmetic Operators

Basic math with numbers:


a = 10
b = 3

print(a + b)   # 13  (addition)
print(a - b)   # 7   (subtraction)
print(a * b)   # 30  (multiplication)
print(a / b)   # 3.333... (true division, always float)
print(a // b)  # 3   (floor division, drops fractional part)
print(a % b)   # 1   (modulo / remainder)
print(a ** b)  # 1000 (exponent / power)
  

Tips:

  • / is always floating-point division. Use // when you want an integer result.
  • Use parentheses to make complex calculations readable.

2) Comparison Operators

Comparisons evaluate to True or False:


x = 7
print(x == 7)   # True   (equal)
print(x != 7)   # False  (not equal)
print(x < 10)   # True   (less than)
print(x > 10)   # False  (greater than)
print(x <= 7)   # True   (less or equal)
print(x >= 8)   # False  (greater or equal)
  

Chaining Comparisons (Pythonic)


age = 18
print(16 <= age < 21)   # True (checks both in one go)
  

3) Logical Operators

Combine boolean expressions with and, or, not. Python uses short-circuit evaluation.


temp = 28
is_raining = False

if temp > 25 and not is_raining:
    print("Great day for a walk!")

# Short-circuit example:
def heavy_check():
    print("Doing heavy check...")
    return True

flag = True
if flag or heavy_check():
    # heavy_check() won't run because flag is True
    print("Short-circuited with OR")
  

4) Assignment Operators

Assign values to names, and use augmented assignment to update in place.


x = 10     # simple assignment

x += 5     # x = x + 5   → 15
x -= 2     # x = x - 2   → 13
x *= 3     # x = x * 3   → 39
x /= 4     # x = x / 4   → 9.75
x //= 2    # x = floor(x / 2) → 4.0
x %= 3     # x = x % 3   → 1.0
x **= 2    # x = x ** 2  → 1.0
  

Multiple Assignment & Unpacking (Pythonic)


# Multiple variables in one line
name, age = "Ammar", 25

# Swap without a temp variable
a, b = 1, 2
a, b = b, a   # a=2, b=1

# Unpack lists/tuples
x, y, z = [10, 20, 30]
  

Optional: Walrus Operator := (Python 3.8+)

Assign and use a value in one expression:


# Read and test in the same expression
while (line := input("Value (blank to stop): ").strip()):
    print("You entered:", line)
  

5) Membership Operators

Check whether a value is contained in a sequence or mapping.


print("py" in "python")            # True  (substring)
print(3 in [1, 2, 3, 4])           # True  (list)
print("id" in {"id": 1, "name": "Ali"})  # True (dict checks KEYS)
print("Ali" in {"id": 1, "name": "Ali"}.values())  # True (values)
print(5 not in (1, 2, 3))          # True
  

Note: in on a dict checks keys by default. Use mydict.values() or mydict.items() to search values or key/value pairs.


6) Identity Operators

Identity checks whether two names refer to the same object in memory, not just equal values.


a = [1, 2, 3]
b = [1, 2, 3]
c = a

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

# Best practice: compare to None using 'is'
x = None
if x is None:
    print("x is not set yet")
  

Rule of thumb: Use == for value comparison. Use is only for identity checks (e.g., with None or singletons).


Operator Precedence (Handy Mini List)

From higher to lower (simplified selection):

  • (...) (parentheses)
  • **
  • unary + - not
  • * / // %
  • + -
  • comparisons < <= > >= == != is in
  • and
  • or

When in doubt, add parentheses for clarity.


Quick Practice (Try Now)

  • Compute: (5 + 3) * 2 ** 2 // 3 and explain the order.
  • Write a check that prints "Allowed" if age is between 18 and 60 (inclusive).
  • Use membership to verify the word "py" is in "python" but not in "java".
  • Show that two identical lists are == equal but not the same object (is).

Key Takeaways

  • Arithmetic: + - * / // % ** — use // for floor division.
  • Comparisons return booleans; you can chain them (e.g., 0 < x < 10).
  • Logical: and, or, not — short-circuit behavior can skip work.
  • Assignment: simple = and augmented forms like +=, plus multiple assignment/unpacking.
  • Membership: in/not in checks sequences; on dicts it checks keys.
  • Identity: is/is not checks object identity; use is None for None checks.
  • Precedence matters — use parentheses for readability and correctness.

Next up: Control Flow — conditions, loops, and loop controls.

Previous: Python Basics

Ahmad Ali

Ahmad Ali

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies Cookie Policy