Operators in Python
Complete guide to Python operators: arithmetic, assignment, comparison, logical, bitwise, identity, membership, conditional expressions, and operator precedence.
Introduction to Operators
Operators are symbols that perform operations on values (operands). They are used to build expressions and logic in Python.
1. What are Operators?
Operators work on operands.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
1. + - * / % // **
Basic arithmetic operators in Python.
Assignment Operators
Assignment operators assign values and can combine with arithmetic.
1. = += -= *= /=
Compound assignment operators.
Comparison Operators
Comparison operators return boolean values.
1. == !=
Equality and inequality.
2. < > <= >=
Relational comparisons.
Logical Operators
Logical operators combine multiple conditions.
1. and or not
Logical operators in Python.
Membership Operators
Python provides membership operators for sequences.
1. in not in
Check presence in list or string.
Identity Operators
Identity operators check whether two variables reference the same object.
1. is is not
Compare object identity.
Conditional Expression
Python supports a compact conditional expression similar to ternary.
1. value1 if condition else value2
Inline conditional.
Bitwise Operators
Bitwise operators work directly on the binary representation of integers. Python integers are not limited to 32 bits like JavaScript, but bitwise operations still follow binary mathematics.
1. Binary Representation (Important Foundation)
Understanding binary numbers is mandatory before learning bitwise operators.
2. Bitwise AND (&)
Returns 1 only if both bits are 1.
3. Bitwise OR (|)
Returns 1 if at least one bit is 1.
4. Bitwise XOR (^)
Returns 1 if bits are different.
5. Bitwise NOT (~)
Inverts all bits using two’s complement.
6. Left Shift (<<)
Shifts bits to the left (multiplies by powers of 2).
7. Right Shift (>>)
Shifts bits to the right (divides by powers of 2).
8. Practical Use Cases
Where bitwise operators are actually used.
Operator Precedence
Precedence determines how expressions are evaluated.
1. Precedence Example
Use parentheses to control order.
2. Operator Precedence Table
Higher precedence operators are evaluated first. When in doubt, use parentheses.