Mastering the Basics: Arithmetic, Comparison, and Logic Operators in Programming”

Jeeshan
“Grokking Python Fundamentals”
12 min read5 days ago

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 adds 10 and 3, giving the result 13.
  • a - b calculates the difference between 10 and 3, resulting in 7.
  • a * b performs multiplication between 10 and 3, resulting in 30.
  • a / b divides 10 by 3, providing a floating point result of approximately 3.333.
  • a % b computes the modulus, which is the remainder when 10 is divided by 3, resulting in 1.
  • a ** b calculates the exponentiation, raising 10 to the power of 3 to get 1000.
  • a // b performs floor division, dividing 10 by 3 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 if 10 is equal to 3, which is false.
  • a != b tests if 10 is not equal to 3, which is true.
  • a > b checks if 10 is greater than 3, which is true.
  • a < b checks if 10 is less than 3, which is false.
  • a >= b checks if 10 is greater than or equal to 3, which is true.
  • a <= b checks if 10 is less than or equal to 3, 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 adds 3 to a, updating a to 13.
  • a -= 2 subtracts 2 from a, updating a to 11.
  • a *= 2 multiplies a by 2, updating a to 22.
  • a /= 2 divides a by 2, updating a to 11.0 (division converts to float).
  • a %= 4 computes the modulus of a divided by 4, updating a to 3.0.
  • a **= 2 raises a to the power of 2, updating a to 9.0.
  • a //= 2 performs floor division of a by 2, updating a to 4.0.
  • a &= 3 performs a bitwise AND with 3, updating a to 0 (since 4 & 3 results in 000).
  • a |= 8 performs a bitwise OR with 8, updating a to 8 (since 000 | 1000 results in 1000).
  • a ^= 6 performs a bitwise XOR with 6, updating a to 14 (since 1000 ^ 0110 results in 1110).
  • a <<= 1 shifts a left by 1 bit, updating a to 28 (doubling the value).
  • a >>= 2 shifts a right by 2 bits, updating a to 7 (effectively dividing by 4 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 to False because with and, both operands must be true, but b is False.
  • a or b evaluates to True because with or, only one operand needs to be true.
  • not a simply negates a, turning True into False.

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 in 2 because the second bit is set in both a and b.
  • 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 in 1 because only one of the corresponding bits is set in either a or b.
  • ~a is the bitwise NOT operation, which inverts all bits of a, leading to -3 (due to two's complement representation).
  • a << 1 shifts all bits in a left by one position, doubling the number to 4.
  • a >> 1 shifts all bits in a right by one position, halving the number to 1

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 if 3 is a member of the list [1, 2, 3, 4, 5], which is true.
  • 6 not in list checks if 6 is not a member of the list, which is true since 6 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 if a and b refer to the same object, which is false because they are equal but not the same object.
  • a is c confirms that a and c refer to the same object, which is true since c is assigned to a.
  • a is not b checks if a and b 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 in 900.
  • b * 900 is next, producing 18000.
  • 18000 / 10 is calculated, yielding 1800.
  • a + 1800 gives 1810.
  • 1810 - 5 results in 1805.
  • 1805 <= b is evaluated (False since 1805 is not less than or equal to 20).
  • b % a == 0 checks if 20 is divisible by 10 without remainder (True).
  • c > b is True since 30 is greater than 20.
  • True and True is True.
  • False or True results in True.
  • The result variable is True because the logical OR operation returns True if at least one of its operands is True.

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.

--

--

Jeeshan
“Grokking Python Fundamentals”

Data Analyst Enthusiast | Unveiling Insights Through Numbers | Helping You Navigate the World of Data Science | Exploring the Frontiers of ML and Generative AI