Mastering the Basics: Arithmetic, Comparison, and Logic Operators in Programming”
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` |
a = 10
b = 3
print(a + b) # Adds 10 and 3, outputting 13
print(a - b) # Subtracts 3 from 10, outputting 7
print(a * b) # Multiplies 10 by 3, outputting 30
print(a / b) # Divides 10 by 3, outputting approximately 3.333
print(a % b) # Finds the remainder of 10 divided by 3, outputting 1
print(a ** b) # Calculates 10 raised to the power of 3, outputting 1000
print(a // b) # Performs floor division of 10 by 3, outputting 3
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.
Here is the information formatted into a table:
| **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` |
a = 10
b = 3
print(a == b) # Compares 10 and 3, checking equality: False
print(a != b) # Compares 10 and 3, checking inequality: True
print(a > b) # Checks if 10 is greater than 3: True
print(a < b) # Checks if 10 is less than 3: False
print(a >= b) # Checks if 10 is greater than or equal to 3: True
print(a <= b) # Checks if 10 is less than or equal to 3: False
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.
Here is the information formatted into a table:
| **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 |= b` |
| `^=` | Bitwise XOR and assignment | `a ^= b` |
| `<<=` | Left shift and assignment | `a <<= b` |
| `>>=` | Right shift and assignment | `a >>= b` |
This table provides a clear and concise reference for various assignment operators, their descriptions, and examples of their usage.
a = 10
a += 3 # a becomes 13
print("a += 3:", a)
a -= 2 # a becomes 11
print("a -= 2:", a)
a *= 2 # a becomes 22
print("a *= 2:", a)
a /= 2 # a becomes 11
print("a /= 2:", a)
a %= 4 # a becomes 3
print("a %= 4:", a)
a **= 2 # a becomes 9
print("a **= 2:", a)
a //= 2 # a becomes 4.0
print("a //= 2:", a)
a = int(a) # Convert a to an integer to use bitwise operators
a &= 3 # a becomes 0 (4 & 3 -> 000 & 011 -> 000)
print("a &= 3:", a)
a |= 8 # a becomes 8 (000 | 1000 -> 1000)
print("a |= 8:", a)
a ^= 6 # a becomes 14 (1000 ^ 0110 -> 1110)
print("a ^= 6:", a)
a <<= 1 # a becomes 28 (1110 << 1 -> 11100)
print("a <<= 1:", a)
a >>= 2 # a becomes 7 (11100 >> 2 -> 111)
print("a >>= 2:", a)
print("Final value of a:", a)
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.
Here is the information formatted into a table:
| **Operator** | **Description** | **Example** |
| — — — — — — — | — — — — — — — — -| — — — — — — -|
| `and` | Logical AND | `a and b` |
| `or` | Logical OR | `a or b` |
| `not` | Logical NOT | `not a` |
a = True
b = False
print(a and b) # False, both need to be True
print(a or b) # True, one of them is True
print(not a) # False, negates True
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.
Here’s a table that shows the result of various bitwise operations for example integers `a` and `b`. Let’s use `a = 12` (which is `1100` in binary) and `b = 7` (which is `0111` in binary) for illustration:
| Operator | Description | Expression | Binary Operation | Result (Decimal) | Result (Binary) |
| — — — — — | — — — — — — — — — — — — — — — | — — — — — — | — — — — — — — — — — — — — | — — — — — — — — — | — — — — — — — — -|
| `&` | Bitwise AND | `a & b` | `1100 & 0111` | `4` | `0100` |
| `|` | Bitwise OR | `a | b` | `1100 | 0111` | `15` | `1111` |
| `^` | Bitwise XOR | `a ^ b` | `1100 ^ 0111` | `11` | `1011` |
| `~` | Bitwise NOT | `~a` | `~1100` | `-13` | `…11110011` |
| `<<` | Left Shift | `a << 2` | `1100 << 2` | `48` | `110000` |
| `>>` | Right Shift | `a >> 2` | `1100 >> 2` | `3` | `0011` |
a = 2 # 0010 in binary
b = 3 # 0011 in binary
print(a & b) # 0010, which is 2
print(a | b) # 0011, which is 3
print(a ^ b) # 0001, which is 1
print(~a) # -3, flips all bits
print(a << 1) # 0100, which is 4 (shift left by 1 bit)
print(a >> 1) # 0001, which is 1 (shift right by 1 bit)
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.).
Sure, here’s a table with the operators “in” and “not in” along with their descriptions and examples:
| 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 |
This table summarizes the `in` and `not in` operators in Python.
list = [1, 2, 3, 4, 5]
print(3 in list) # True
print(6 not in list) # True
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.
Sure, here’s the complete table including the `in`, `not in`, `is`, and `is not` operators:
| 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 |
| is | True if both sides are the same object | a is b |
| is not | True if sides are different objects | a is not b |
This table summarizes the `in`, `not in`, `is`, and `is not` operators in Python.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # False
print(a is c) # True
print(a is not b) # True
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, minus, NOT | `+x`, `-x`, `~x` |
| 4 | Multiplicative | `*`, `/`, `%`, `//` |
| 5 | Additive | `+`, `-` |
| 6 | Bitwise shifts | `<<`, `>>` |
| 7 | Bitwise AND | `&` |
| 8 | Bitwise OR, XOR | `|`, `^` |
| 9 | Comparison | `==`, `!=`, `>`, `<`, `>=`, `<=` |
| 10 | Equality | `is`, `is not` |
| 11 | Membership | `in`, `not in` |
| 12 | Logical NOT | `not` |
| 13 | Logical AND | `and` |
| 14 | Logical OR | `or` |
This table outlines the order in which Python evaluates different types of operators.
Example
a = 10
b = 20
c = 30
result = a + b * c ** 2 / 10 - 5 <= b or b % a == 0 and c > b
print(result)
- 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.