โž•Operators: Arithmetic, Comparison, LogicalLESSON

Operators: Arithmetic, Comparison, Logical

Operators are the symbols that tell Python to perform specific computations. Python has a rich set of operators that cover arithmetic, comparisons, logic, and more.

Arithmetic Operators

Floor Division and Modulo with Negatives

Floor division rounds toward negative infinity, not toward zero:

Modulo follows the sign of the divisor:

Useful Arithmetic Patterns

Comparison Operators

Comparison operators return True or False:

Chained Comparisons

Python supports chaining comparison operators naturally:

Identity vs Equality

Logical Operators

Short-Circuit Evaluation

Python's and and or use short-circuit evaluation โ€” they stop as soon as the result is determined:

Practical Uses of Short-Circuit

Bitwise Operators

Bitwise operators work on the binary representation of integers:

Common bitwise patterns:

Operator Precedence

When operators appear together, Python uses precedence rules (highest to lowest):

PrecedenceOperators
Highest** (exponentiation)
~, unary +, unary -
*, /, //, %
+, -
<<, >>
&
^
`
==, !=, <, >, <=, >=, is, in
not
and
Lowestor

Knowledge Check

What is the result of -17 // 5 in Python?

What does the expression (0 or 'default') evaluate to?

Which statement about chained comparisons like (1 < x < 10) is correct?