0% completed
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.
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 + b
adds10
and3
, giving the result13
.a - b
calculates the difference between10
and3
, resulting in7
.a * b
performs multiplication between10
and3
, resulting in30
.a / b
divides10
by3
, providing a floating point result of approximately3.333
.a % b
computes the modulus, which is the remainder when10
is divided by3
, resulting in1
.a ** b
calculates the exponentiation, raising10
to the power of3
to get1000
.a // b
performs floor division, dividing10
by3
and 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 == b
tests if10
is equal to3
, which is false.a != b
tests if10
is not equal to3
, which is true.a > b
checks if10
is greater than3
, which is true.a < b
checks if10
is less than3
, which is false.a >= b
checks if10
is greater than or equal to3
, which is true.a <= b
checks if10
is 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 += 3
adds3
toa
, updatinga
to13
.a -= 2
subtracts2
froma
, updatinga
to11
.a *= 2
multipliesa
by2
, updatinga
to22
.a /= 2
dividesa
by2
, updatinga
to11.0
(division converts to float).a %= 4
computes the modulus ofa
divided by4
, updatinga
to3.0
.a **= 2
raisesa
to the power of2
, updatinga
to9.0
.a //= 2
performs floor division ofa
by2
, updatinga
to4.0
.a &= 3
performs a bitwise AND with3
, updatinga
to0
(since4 & 3
results in000
).a |= 8
performs a bitwise OR with8
, updatinga
to8
(since000 | 1000
results in1000
).a ^= 6
performs a bitwise XOR with6
, updatinga
to14
(since1000 ^ 0110
results in1110
).a <<= 1
shiftsa
left by1
bit, updatinga
to28
(doubling the value).a >>= 2
shiftsa
right by2
bits, updatinga
to7
(effectively dividing by4
and 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 b
evaluates toFalse
because withand
, both operands must be true, butb
isFalse
.a or b
evaluates toTrue
because withor
, only one operand needs to be true.not a
simply negatesa
, turningTrue
intoFalse
.
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 & b
performs a bitwise AND, which results in2
because the second bit is set in botha
andb
.a | b
performs a
bitwise OR, resulting in 3
because at least one of the corresponding bits is set.
a ^ b
performs a bitwise XOR, resulting in1
because only one of the corresponding bits is set in eithera
orb
.~a
is the bitwise NOT operation, which inverts all bits ofa
, leading to-3
(due to two's complement representation).a << 1
shifts all bits ina
left by one position, doubling the number to4
.a >> 1
shifts all bits ina
right 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 list
checks if3
is a member of the list[1, 2, 3, 4, 5]
, which is true.6 not in list
checks if6
is not a member of the list, which is true since6
is 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 b
checks ifa
andb
refer to the same object, which is false because they are equal but not the same object.a is c
confirms thata
andc
refer to the same object, which is true sincec
is assigned toa
.a is not b
checks ifa
andb
are 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 ** 2
is calculated first because**
has the highest precedence among the operators used, resulting in900
.b * 900
is next, producing18000
.18000 / 10
is calculated, yielding1800
.a + 1800
gives1810
.1810 - 5
results in1805
.1805 <= b
is evaluated (False
since1805
is not less than or equal to20
).b % a == 0
checks if20
is divisible by10
without remainder (True
).c > b
isTrue
since30
is greater than20
.True and True
isTrue
.False or True
results inTrue
.
- The
result
variable isTrue
because the logical OR operation returnsTrue
if 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.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible