Python operators are special symbols and keywords that compute values, compare objects, and combine conditions. Understanding operator behavior saves you from subtle math bugs and precedence errors.
Python splits operators into clear groups: arithmetic (+, -, *, /, //, %, **), assignment (=, +=), comparison (==, !=, <, >), logical (and, or, not), identity (is), and membership (in).
Floor division // drops the remainder, modulo % returns the remainder, and ** raises a number to a power. Membership (in) checks lists, strings, sets, and dictionary keys.
total_minutes = 135
hours = total_minutes // 60 # 2
minutes = total_minutes % 60 # 15
square_area = 6 ** 2 # 36
allowed_roles = {"admin", "editor"}
print(f"{hours}h {minutes}m", square_area, "admin" in allowed_roles)
Python evaluates ** before *, /, //, %, which run before + and -. Comparisons run after arithmetic, and not runs before and, which runs before or.
Always add parentheses when mixing multiple logical or arithmetic operators so readers never have to guess evaluation order.
^ for exponentiation: In Python, ^ is bitwise XOR, not power; always use ** (2 ** 3 == 8).is on numbers or strings: x is 1000 can return False even when x == 1000; reserve is for None and singletons.a or b and c groups as a or (b and c), which often surprises readers.:= do?The assignment expression operator := assigns a value to a variable inside an expression, such as if (n := len(items)) > 5:.
= and == differ?= assigns a value to a variable name, whereas == compares two values and returns True or False.
+= do on a list vs a tuple?On a mutable list, nums += [4] updates the list in place. On an immutable tuple, t += (4,) creates and rebinds a new tuple.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.