Lesson

Python Operators

10 min reading
Free Course

Python Operators: Arithmetic, Logic, Membership, and Precedence

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).

Essential Operators in Action

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)

Operator Precedence and Clarity

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.

Common Mistakes to Avoid

  • Using ^ for exponentiation: In Python, ^ is bitwise XOR, not power; always use ** (2 ** 3 == 8).
  • Chaining is on numbers or strings: x is 1000 can return False even when x == 1000; reserve is for None and singletons.
  • Omitting parentheses in complex conditions: a or b and c groups as a or (b and c), which often surprises readers.

Frequently Asked Questions

What does the walrus operator := do?

The assignment expression operator := assigns a value to a variable inside an expression, such as if (n := len(items)) > 5:.

How do = and == differ?

= assigns a value to a variable name, whereas == compares two values and returns True or False.

What does += 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum