Introduction to Python Operators
Operators in Python are special symbols that perform operations on one or more operands. Operands are the values or variables with which these operators are applied to produce a result. Operators are the building blocks of Python expressions and are essential for performing calculations, making decisions, manipulating data, and more. Python supports a wide range of operators, each serving different purposes:
- Arithmetic Operators: Perform basic mathematical operations.
- Comparison (Relational) Operators: Compare two values and determine their relationship.
- Assignment Operators: Assign values to variables.
- Logical Operators: Combine conditional statements.
- Bitwise Operators: Perform bitwise calculations on integers.
- Membership Operators: Test membership in sequences such as lists or strings.
- Identity Operators: Compare the memory locations of two objects.
Image scaled to 60%
In this lesson, we will explore each type of operator, providing definitions, usage examples, and detailed explanations of how they work in Python. This foundational knowledge will help you write more efficient and effective Python code.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and more between numbers.
| Operator | Description | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
** | Exponentiation | a ** b |
// | Floor division | a // b |
Example
Explanation:
a + badds10and3, giving the result13.a - bcalculates the difference between10and3, resulting in7.a * bperforms multiplication between10and3, resulting in30.a / bdivides10by3, providing a floating point result of approximately3.333.a % bcomputes the modulus, which is the remainder when10is divided by3, resulting in1.a ** bcalculates the exponentiation, raising10to the power of3to get1000.a // bperforms floor division, dividing10by3and rounding down to the nearest whole number,3.
Comparison (Relational) Operators
Comparison operators are used to compare two values, outputting a Boolean value based on whether the comparison is true or false.
| Operator | Description | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Example
Explanation:
a == btests if10is equal to3, which is false.a != btests if10is not equal to3, which is true.a > bchecks if10is greater than3, which is true.a < bchecks if10is less than3, which is false.a >= bchecks if10is greater than or equal to3, which is true.a <= bchecks if10is less than or equal to3, which is false.
Assignment Operators
Assignment operators in Python are used to assign values to variables, often simplifying code by combining standard operations with an assignment.
| Operator | Description | Example |
|---|---|---|
= | Simple assignment | a = b |
+= | Addition and assignment | a += b |
-= | Subtraction and assignment | a -= b |
*= | Multiplication and assignment | a *= b |
/= | Division and assignment | a /= b |
%= | Modulus and assignment | a %= b |
**= | Exponent and assignment | a **= b |
//= | Floor division and assignment | a //= b |
&= | Bitwise AND and assignment | a &= b |
|= | Bitwise OR and assignment | `a |
^= | Bitwise XOR and assignment | a ^= b |
<<= | Left shift and assignment | a <<= b |
>>= | Right shift and assignment | a >>= b |
Example
Explanation:
a += 3adds3toa, updatingato13.a -= 2subtracts2froma, updatingato11.a *= 2multipliesaby2, updatingato22.a /= 2dividesaby2, updatingato11.0(division converts to float).a %= 4computes the modulus ofadivided by4, updatingato3.0.a **= 2raisesato the power of2, updatingato9.0.a //= 2performs floor division ofaby2, updatingato4.0.a &= 3performs a bitwise AND with3, updatingato0(since4 & 3results in000).a |= 8performs a bitwise OR with8, updatingato8(since000 | 1000results in1000).a ^= 6performs a bitwise XOR with6, updatingato14(since1000 ^ 0110results in1110).a <<= 1shiftsaleft by1bit, updatingato28(doubling the value).a >>= 2shiftsaright by2bits, updatingato7(effectively dividing by4and truncating towards zero).
Logical Operators
Logical operators are used to combine conditional statements in Python. They are fundamental in expressing compound conditions.
| Operator | Description | Example |
|---|---|---|
and | Logical AND | a and b |
or | Logical OR | a or b |
not | Logical NOT | not a |
Example
Explanation:
a and bevaluates toFalsebecause withand, both operands must be true, butbisFalse.a or bevaluates toTruebecause withor, only one operand needs to be true.not asimply negatesa, turningTrueintoFalse.
Bitwise Operators
Bitwise operators are used to perform bit-level operations on integers. They manipulate individual bits of these numbers.
| Operator | Description | Example |
|---|---|---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~a |
<< | Left Shift | a << b |
>> | Right Shift | a >> b |
Example
Explanation:
a & bperforms a bitwise AND, which results in2because the second bit is set in bothaandb.a | bperforms a
bitwise OR, resulting in 3 because at least one of the corresponding bits is set.
a ^ bperforms a bitwise XOR, resulting in1because only one of the corresponding bits is set in eitheraorb.~ais the bitwise NOT operation, which inverts all bits ofa, leading to-3(due to two’s complement representation).a << 1shifts all bits inaleft by one position, doubling the number to4.a >> 1shifts all bits inaright by one position, halving the number to1.
Membership Operators
Membership operators in Python are used to test whether a value or variable is found in a sequence (string, list, tuple, etc.).
| Operator | Description | Example |
|---|---|---|
in | True if value is in sequence | x in y |
not in | True if value is not in sequence | x not in y |
Example
Explanation:
3 in listchecks if3is a member of the list[1, 2, 3, 4, 5], which is true.6 not in listchecks if6is not a member of the list, which is true since6is absent.
Identity Operators
Identity operators compare the memory locations of two objects. They are used to check if objects are actually the same instance, beyond just having equal value.
| Operator | Description | Example |
|---|---|---|
is | True if both sides are the same object | a is b |
is not | True if sides are different objects | a is not b |
Example
Explanation:
a is bchecks ifaandbrefer to the same object, which is false because they are equal but not the same object.a is cconfirms thataandcrefer to the same object, which is true sincecis assigned toa.a is not bchecks ifaandbare not the same object, which is true as they are different instances.
Python Operator Precedence
Operator precedence in Python determines the order in which operations are processed. This can affect the outcome of expressions where multiple operators appear. Higher precedence operators are executed before lower precedence ones.
Here’s a simplified list of Python operator precedence, from highest to lowest:
| Precedence | Operator Type | Operators |
|---|---|---|
| 1 | Parentheses | () |
| 2 | Exponentiation | ** |
| 3 | Unary plus, Unary minus, Bitwise NOT | +x, -x, ~x |
| 4 | Multiplicative | *, /, %, // |
| 5 | Additive | +, - |
| 6 | Bitwise shifts | <<, >> |
| 7 | Bitwise AND, OR, XOR | &, |, ^ |
| 8 | Comparison | ==, !=, >, <, >=, <= |
| 9 | Equality | is, is not |
| 10 | Membership | in, not in |
| 11 | Logical NOT | not |
| 12 | Logical AND | and |
| 13 | Logical OR | or |
Example
Explanation:
- This example evaluates using Python’s operator precedence rules:
c ** 2is calculated first because**has the highest precedence among the operators used, resulting in900.b * 900is next, producing18000.18000 / 10is calculated, yielding1800.a + 1800gives1810.1810 - 5results in1805.1805 <= bis evaluated (Falsesince1805is not less than or equal to20).b % a == 0checks if20is divisible by10without remainder (True).c > bisTruesince30is greater than20.True and TrueisTrue.False or Trueresults inTrue.
- The
resultvariable isTruebecause the logical OR operation returnsTrueif at least one of its operands isTrue.
Understanding operator precedence is essential for writing clear and correct Python code, especially in complex expressions. It ensures that you can predict and control the order of operations without excessive use of parentheses.