Python - Operators

9 minute read

Python, a versatile and powerful programming language, has a plethora of operators that allow developers to perform various operations. Understanding these operators is crucial for writing efficient and readable code. Whether you’re manipulating numbers, comparing values, or performing complex logical operations, Python’s operators are the tools you’ll rely on. In this article, we’ll explore these operators in detail, complete with examples to illustrate their usage.

Basic Arithmetic Operators

Arithmetic operators are the building blocks of mathematical operations in Python.

Addition (+)

Addition is used to sum two numbers.

a = 10
b = 5
result = a + b
print(result)  # Output: 15

In this example, 10 and 5 are added to yield 15.

Subtraction (-)

Subtraction allows you to subtract one number from another.

a = 10
b = 5
result = a - b
print(result)  # Output: 5

Here, 5 is subtracted from 10, resulting in 5.

Multiplication (*)

Multiplication is used to multiply two numbers.

a = 10
b = 5
result = a * b
print(result)  # Output: 50

In this example, 10 is multiplied by 5, resulting in 50.

Division (/)

Division divides one number by another.

a = 10
b = 5
result = a / b
print(result)  # Output: 2.0

10 divided by 5 gives 2.0. Note that division always returns a floating-point number.

Floor Division (//)

Floor division returns the largest integer less than or equal to the division of the two numbers.

a = 10
b = 3
result = a // b
print(result)  # Output: 3

Here, 10 divided by 3 results in 3, discarding the remainder.

Modulus (%)

The modulus operator returns the remainder of the division.

a = 10
b = 3
result = a % b
print(result)  # Output: 1

In this case, the remainder when 10 is divided by 3 is 1.

Exponentiation (``)

Exponentiation raises one number to the power of another.

a = 2
b = 3
result = a  b
print(result)  # Output: 8

2 raised to the power of 3 equals 8.

Comparison Operators

Comparison operators are used to compare two values.

Equal to (==)

Checks if two values are equal.

a = 5
b = 5
print(a == b)  # Output: True

Here, 5 is equal to 5, so the output is True.

Not Equal to (!=)

Checks if two values are not equal.

a = 5
b = 3
print(a != b)  # Output: True

Since 5 is not equal to 3, the output is True.

Greater than (>)

Checks if one value is greater than another.

a = 5
b = 3
print(a > b)  # Output: True

5 is greater than 3, so the output is True.

Less than (<)

Checks if one value is less than another.

a = 3
b = 5
print(a < b)  # Output: True

3 is less than 5, resulting in True.

Greater than or Equal to (>=)

Checks if one value is greater than or equal to another.

a = 5
b = 5
print(a >= b)  # Output: True

Since 5 is equal to 5, the output is True.

Less than or Equal to (<=)

Checks if one value is less than or equal to another.

a = 3
b = 5
print(a <= b)  # Output: True

3 is less than 5, so the output

is True.

Logical Operators

Logical operators are used to combine conditional statements.

Logical AND (and)

Returns True if both conditions are True.

a = 5
print(a > 3 and a < 10)  # Output: True

5 is greater than 3 and less than 10, so the output is True.

Logical OR (or)

Returns True if at least one condition is True.

a = 5
print(a > 3 or a < 4)  # Output: True

5 is greater than 3, so the output is True.

Logical NOT (not)

Reverses the boolean value.

a = 5
print(not(a > 3))  # Output: False

a > 3 is True, so not(a > 3) is False.

Bitwise Operators

Bitwise operators perform operations on binary numbers.

Bitwise AND (&)

Performs a bitwise AND operation.

a = 5  # 0101 in binary
b = 3  # 0011 in binary
print(a & b)  # Output: 1 (0001 in binary)

The result is 1, as the only common 1 bit is in the lowest position.

Bitwise OR (|)

Performs a bitwise OR operation.

a = 5  # 0101 in binary
b = 3  # 0011 in binary
print(a | b)  # Output: 7 (0111 in binary)

The result is 7, as all 1 bits from both numbers are combined.

Bitwise XOR (^)

Performs a bitwise XOR operation.

a = 5  # 0101 in binary
b = 3  # 0011 in binary
print(a ^ b)  # Output: 6 (0110 in binary)

The result is 6, as different bits are combined.

Bitwise NOT (~)

Inverts all bits.

a = 5  # 0101 in binary
print(~a)  # Output: -6

The result is -6 because of the way negative numbers are represented in binary (two’s complement).

Bitwise Left Shift (<<)

Shifts bits to the left, filling with zeros.

a = 5  # 0101 in binary
print(a << 1)  # Output: 10 (1010 in binary)

5 is shifted left by 1 position, resulting in 10.

Bitwise Right Shift (>>)

Shifts bits to the right, discarding bits.

a = 5  # 0101 in binary
print(a >> 1)  # Output: 2 (0010 in binary)

5 is shifted right by 1 position, resulting in 2.

Assignment Operators

Assignment operators are used to assign values to variables.

Assignment (=)

Assigns the value to the variable.

a = 5
print(a)  # Output: 5

5 is assigned to a.

Add and Assign (+=)

Adds and assigns the value.

a = 5
a += 3
print(a)  # Output: 8

3 is added to a and assigned back to a.

Subtract and Assign (-=)

Subtracts and assigns the value.

a = 5
a -= 3
print(a)  # Output: 2

3 is subtracted from a and assigned back to a.

Multiply and Assign (*=)

Multiplies and assigns the value.

a = 5
a *= 3
print(a)  # Output: 15

a is multiplied by 3 and assigned back to a.

Divide and Assign (/=)

Divides and assigns the value.

a = 5
a /= 2
print(a)  # Output: 2.5

a is divided by 2 and assigned back to a.

Floor Divide and Assign (//=)

Floor divides and assigns the value.

a = 5
a //= 2
print(a)  # Output: 2

a is floor divided by 2 and assigned back to a.

Modulus and Assign (%=)

Applies modulus and assigns the value.

a = 5
a %= 3
print(a)  # Output: 2

a modulus 3 is assigned back to a.

Exponentiate and Assign (=)

Exponentiates and assigns the value.

a = 5
a = 2
print(a)  # Output: 25

a is raised to the power of 2 and assigned back to a.

Bitwise AND and Assign (&=)

Performs bitwise AND and assigns the value.

a = 5
a &= 3
print(a)  # Output: 1

a bitwise AND 3 is assigned back to a.

Bitwise OR and Assign (|=)

Performs bitwise OR and assigns the value.

a = 5
a |= 3
print(a)  # Output: 7

a bitwise OR 3 is assigned back to a.

Bitwise XOR and Assign (^=)

Performs bitwise XOR and assigns the value.

a = 5
a ^= 3
print(a)  # Output: 6

a bitwise XOR 3 is assigned back to a.

Bitwise Left Shift and Assign (<<=)

Left shifts and assigns the value.

a = 5
a <<= 1
print(a)  # Output: 10

a is left shifted by 1 and assigned back to a.

Bitwise Right Shift and Assign (>>=)

Right shifts and assigns the value.

a = 5
a >>= 1
print(a)  # Output: 2

a is right shifted by 1 and assigned back to a.

Identity Operators

Identity operators compare the memory locations of two objects.

Is (is)

Checks if two variables point to the same object.

a = [1, 2, 3]
b = a
print(a is b)  # Output: True

a and b refer to the same object, so is returns True.

Is Not (is not)

Checks if two variables point to different objects.

a = [1, 2, 3]
b = [1, 2, 3]
print(a is not b)  # Output: True

a and b are different objects with the same content, so is not returns True.

Membership Operators

Membership operators test for membership in a sequence.

In (in)

Checks if a value is present in a sequence.

a = [1, 2, 3]
print(2 in a)  # Output: True

2 is in the list a, so in returns True.

Not In (not in)

Checks if a value is not present in a sequence.

a = [1, 2, 3]
print(4 not in a)  # Output: True

4 is not in the list a, so not in returns True.

Ternary Conditional Operator

The ternary operator provides a concise way to perform conditional assignments.

Conditional Expression

a = 5
b = 10
max_value = a if a > b else b
print(max_value)  # Output: 10

max_value is assigned a if a is greater than b, otherwise b. Here, b is greater, so max_value is 10.

Operator Precedence

Operator precedence determines the order in which operations are performed.

Explanation of Operator Precedence

Operators have a specific precedence level that dictates their order of evaluation in an expression.

Example: Combining Different Operators

a = 5 + 2 * 3  # Output: 11 (Multiplication first, then addition)
print(a)

Here, multiplication (*) is performed before addition (+), resulting in 11.

Conclusion

Understanding Python operators is essential for effective programming. They form the foundation of manipulating data and control flow in your code. By mastering these operators, you can write more concise and efficient programs.

FAQs

1. What is the difference between == and = in Python?
== is used for comparison, checking if two values are equal, while = is used for assignment, assigning a value to a variable.

2. How does the floor division operator (//) differ from regular division (/)?
Floor division (//) returns the largest integer less than or equal to the division result, while regular division (/) returns a floating-point number.

3. Can you chain comparison operators in Python?
Yes, you can chain comparison operators, like a < b < c, which checks if a is less than b and b is less than c.

4. What are the common uses of bitwise operators?
Bitwise operators are commonly used for tasks involving binary manipulation, such as setting or clearing specific bits, and for performance optimizations in low-level programming.

5. How can I remember the order of operations in Python?
You can remember the order of operations using the acronym PEMDAS: Parentheses, Exponents, Multiplication/Division (left to right), and Addition/Subtraction (left to right).

Updated: