Contents

Operators in Python

Operators

In Python, operators are symbols that perform specific computations or operations on variables and values, acting as essential tools in programming.

  • Operator: Special symbol used to perform operations, like +, -, *, /.
  • Operand: Value on which the operator acts.
Types of Operators in Python
  • Arithmetic
  • Operators
  • Comparison
  • Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity and Membership Operators
Arithmetic Operators in Python

These operators help perform basic arithmetic tasks such as addition, subtraction, multiplication, and division.

In Python 3.x, the division operator / returns a floating-point result, while // returns a floored integer result.

OperatorDescriptionSyntax
+Adds two valuesx + y
Subtracts second value from the firstx - y
*Multiplies two valuesx * y
/Divides first value by the second (float)x / y
//Divides first value by second (floor)x // y
%Returns remainderx % y
**Raises first value to power of secondx ** y

Example: Performing Arithmetic Operations

				
					a = 12
b = 5

sum_val = a + b
diff_val = a - b
product_val = a * b
quotient_val = a / b
floor_div = a // b
modulus_val = a % b
power_val = a ** b

print("Sum:", sum_val)
print("Difference:", diff_val)
print("Product:", product_val)
print("Quotient (float):", quotient_val)
print("Quotient (floor):", floor_div)
print("Modulus:", modulus_val)
print("Power:", power_val)

				
			

Output:

				
					Sum: 17
Difference: 7
Product: 60
Quotient (float): 2.4
Quotient (floor): 2
Modulus: 2
Power: 248832

				
			
Comparison Operators

Comparison operators compare values and return True or False based on the condition.

OperatorDescriptionSyntax
>True if left value is greaterx > y
<True if left value is smallerx < y
==True if values are equalx == y
!=True if values are not equalx != y
>=True if left value is greater or equalx >= y
<=True if left value is smaller or equalx <= y

Example: Using Comparison Operators

				
					x = 15
y = 20

print("Is x greater than y?", x > y)
print("Is x less than y?", x < y)
print("Is x equal to y?", x == y)
print("Is x not equal to y?", x != y)
print("Is x greater than or equal to y?", x >= y)
print("Is x less than or equal to y?", x <= y)

				
			

Output:

				
					Is x greater than y? False
Is x less than y? True
Is x equal to y? False
Is x not equal to y? True
Is x greater than or equal to y? False
Is x less than or equal to y? True

				
			
Logical Operators

Logical operators combine conditional expressions.

OperatorDescriptionSyntax
andTrue if both conditions are truex and y
orTrue if either condition is truex or y
notTrue if condition is falsenot x

Example: Logical Operations with Conditions

				
					a = True
b = False

print("a and b:", a and b)
print("a or b:", a or b)
print("not a:", not a)

				
			

Output:

				
					a and b: False
a or b: True
not a: False

				
			
Bitwise Operators

These operators perform bit-by-bit operations.

OperatorDescriptionSyntax
&Bitwise ANDx & y
|Bitwise OR`x
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx >> y
<<Bitwise left shiftx << y

Example: Applying Bitwise Operations

				
					a = 5
b = 3

print("a & b:", a & b)
print("a | b:", a | b)
print("~a:", ~a)
print("a ^ b:", a ^ b)
print("a >> 1:", a >> 1)
print("a << 1:", a << 1)

				
			

Output:

				
					a & b: 1
a | b: 7
~a: -6
a ^ b: 6
a >> 1: 2
a << 1: 10

				
			
Assignment Operators

These operators assign values to variables, often combining an arithmetic operation.

OperatorDescriptionSyntax
=Simple assignmentx = y
+=Add and assignx += y
-=Subtract and assignx -= y
*=Multiply and assignx *= y
/=Divide and assign (float)x /= y
//=Divide and assign (floor)x //= y
%=Modulus and assignx %= y
**=Exponent and assignx **= y
&=Bitwise AND and assignx &= y
|=Bitwise OR and assign`x
^=Bitwise XOR and assignx ^= y
>>=Right shift and assignx >>= y
<<=Left shift and assignx <<= y

Example: Using Assignment Operators

				
					x = 10
y = 3

x += y
print("After += :", x)

x -= y
print("After -= :", x)

x *= y
print("After *= :", x)

x //= y
print("After //= :", x)

				
			

Output:

				
					After += : 13
After -= : 10
After *= : 30
After //= : 10

				
			
Identity Operators

Identity operators check if two variables point to the same object in memory.

OperatorDescription
isTrue if both are identical
is notTrue if they are not

Example: Checking Object Identity

				
					a = 100
b = 100
c = a

print("a is b:", a is b)
print("a is c:", a is c)

				
			

Output:

				
					a is b: True
a is c: True

				
			
Membership Operators

Membership operators check if a value is in a sequence, like a list or a string.

OperatorDescription
inTrue if value is in sequence
not inTrue if value is not in sequence

Example: Checking Membership in a List

				
					fruits = ["apple", "banana", "cherry"]
fruit = "banana"

print("Is 'banana' in fruits?", fruit in fruits)
print("Is 'orange' not in fruits?", "orange" not in fruits)

				
			

Output:

				
					Is 'banana' in fruits? True
Is 'orange' not in fruits? True

				
			

Difference between / vs. // operator in Python

In this article, we’ll explore the difference between the division operator / and the floor division operator // in Python.

Standard Division in Python (/ Operator)

The division operator / in Python performs classic division, yielding a floating-point result, even when dividing two integers. It calculates the precise value by including the decimal part.

Example

				
					# Division operator
result = 9 / 4
print(result)

				
			

Output:

				
					2.25

				
			
Floor Division in Python (// Operator)

The floor division operator //, on the other hand, performs division and rounds down to the nearest integer. This means that it removes the decimal part entirely, always resulting in an integer. Floor division can be helpful when you need integer results without rounding up, as it returns the largest whole number less than or equal to the result.

Example:

				
					# Floor division operator
result1 = 9 // 4
print("Floor division result:", result1)

				
			

Output:

				
					Floor division result: 2

				
			
Summary of Differences Between / and // in Python

Below is a comparison table highlighting the main differences between these two operators.

FeatureDivision Operator (/)Floor Division Operator (//)
Return TypeFloat (even if the operands are integers)Integer
Fractional PartKeeps the fractional partDiscards the fractional part
Examples7 / 3 = 2.3333...
8 / 4 = 2.0
6 / 2 = 3.0
-9 / 4 = -2.25
7 // 3 = 2
8 // 4 = 2
6 // 2 = 3
-9 // 4 = -3

Using these operators depends on the need for precision in your calculation: / is used when you need the exact decimal, while // is for cases where only the integer part is required.

Python Star or Asterisk operator ( * )

Uses of the Asterisk (*) in Python:

1. Multiplication: The asterisk (*) can act as a multiplication operator when used between two numbers.

				
					# Using the asterisk for multiplication
product = 8 * 6
print(product)

				
			

Output:

				
					48

				
			

2. Exponentiation: Two asterisks (**) are used to raise a number to the power of another, representing exponentiation.

				
					x = 4
y = 2

# Using double asterisks for exponentiation
power_result = x ** y
print(power_result)

				
			

Output:

				
					16

				
			

3. List Multiplication: By placing an asterisk next to a list, we can repeat the elements in that list a specified number of times.

				
					# Multiplying a list
words = ['hello'] * 4
print(words)

				
			

Output:

				
					['hello', 'hello', 'hello', 'hello']

				
			

4. Unpacking a List for Function Arguments: Using an asterisk in front of a list while passing it to a function allows us to unpack its elements as separate positional arguments.

				
					days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']

# Without unpacking
print(' '.join(days))

# Using asterisk to unpack
print(*days)

				
			

Output:

				
					Monday Tuesday Wednesday Thursday
Monday Tuesday Wednesday Thursday

				
			

5. Passing Multiple Positional Arguments with *args: The asterisk allows a function to accept a variable number of positional arguments. Here, *args can be used to accept any number of arguments and handle them as a tuple.

				
					# Function using *args
def add_numbers(*args):
    return sum(args)

print(add_numbers(2, 8, 15, 5))

				
			

Output:

				
					30

				
			

6. Passing Multiple Keyword Arguments with **kwargs: Two asterisks (**) allow a function to accept a variable number of keyword arguments, making them accessible as a dictionary.

				
					# Function using **kwargs
def describe_food(**kwargs):
    for item, description in kwargs.items():
        print(f"{description} is a {item}")

describe_food(fruit='banana', vegetable='carrot', snack='chips')

				
			

Output:

				
					banana is a fruit
carrot is a vegetable
chips is a snack

				
			

7. Unpacking a Dictionary for Function Arguments Using **: The double asterisk can also unpack a dictionary’s key-value pairs into function arguments, as shown here.

				
					# Function using **kwargs with dictionary unpacking
def display_food_info(**kwargs):
    for item, description in kwargs.items():
        print(f"{description} is a {item}")

food_info = {'fruit': 'apple', 'vegetable': 'spinach', 'grain': 'rice'}

# Unpacking dictionary
display_food_info(**food_info)

				
			

Output

				
					apple is a fruit
spinach is a vegetable
rice is a grain

				
			

Division Operators in Python

Python provides two main types of division operators for handling division between numbers:

1. Float Division (/)
2. Integer (Floor) Division (//)

Advantages of Division Operators in Python

The division operators in Python are powerful and versatile tools in programming. Here are some advantages:

  • Fundamental Arithmetic: They’re essential for performing arithmetic calculations in programming.
  • Simplified Syntax: They offer a clear and concise way to represent division, avoiding more complex expressions.
  • Precision Control: With / for floating-point division and // for integer division, they provide control over the type of result.
  • Algorithmic Efficiency: They help in efficient computations, useful in mathematical modeling, machine learning, and data analysis.
  • Versatile Modeling: They can be applied to simulate complex systems and analyze phenomena with precision control.
Types of Division Operators in Python

1. Float Division (/): Using the / operator results in a float, even if both operands are integers.

Example:

				
					# Float division examples
print(8 / 2)
print(15 / 3)
print(-9 / 3)
print(18.0 / 2)

				
			

Output:

				
					4.0
5.0
-3.0
9.0

				
			

2. Integer (Floor) Division (//) : The // operator performs integer division, also known as floor division. If one of the operands is a float, the result will be a float. When applied to a negative number, it returns the closest integer less than or equal to the quotient.

Example:

				
					# Integer (floor) division examples
print(9 // 2)
print(17 // 3)
print(-7 // 3)

				
			

Output:

				
					4
5
-3

				
			

Division Operators in Python

Division Operator on Boolean Values in Python

Python does not support division for boolean values. Attempting to divide boolean values will result in a TypeError. However, you can overload the division operator for a custom class to define specific behavior.

Example: Custom Division Operator Overload with Boolean Values

In the following code, a custom class CustomBool is created. The division operator (/) is overloaded to perform a logical operation between two boolean values.

				
					class CustomBool:
    def __init__(self, value):
        self.value = bool(value)

    def __truediv__(self, other):
        # Logical AND operation between two boolean values
        return CustomBool(self.value and other.value)

# Create instances
a = CustomBool(True)
b = CustomBool(False)
result = a / b  # result.value will be False

print(result.value)

				
			

Output:

				
					False

				
			

Modulo operator (%) in Python

In Python, the % symbol represents the modulo operator, which calculates the remainder of a division operation. This is not to be confused with the “percent” symbol. When you see a % b, it means that a is divided by b, and the result is the remainder of this division.

What is the Python Modulo Operator?

The Python modulo operator, %, provides the remainder from the division of two numbers and is part of the arithmetic operations family alongside +, -, /, *, **, and //. Unlike many programming languages, the modulo operator in Python works with both integers and floats.

Syntax:

				
					result = a % b

				
			

Example:

				
					# Example with integer operands
num1 = 16
num2 = 7

result = num1 % num2
print(num1, "mod", num2, "=", result, sep=" ")

				
			

Output:

				
					16 mod 7 = 2

				
			
Modulo Operator with Floating-Point Numbers and Negative Values

The modulo operator can handle floating-point numbers, and when negative numbers are involved, the result takes on the sign of the divisor.

				
					# Example with floating-point operands and a negative divisor
float_num1 = 22.5
float_num2 = -8.0

result = float_num1 % float_num2
print(float_num1, "mod", float_num2, "=", result, sep=" ")

				
			

Output:

				
					22.5 mod -8.0 = -5.5

				
			
Practical Example Using the Modulo Operator

Suppose we want to compute the remainder when dividing each number from 1 to n by a given divisor k. This example demonstrates how to calculate and display these remainders:

				
					# Define function to calculate remainders from 1 to n divided by k
def calculate_remainders(n, k):
    for i in range(1, n + 1):
        remainder = i % k
        print(i, "mod", k, "=", remainder, sep=" ")

# Calling the function
n = 7
k = 4
calculate_remainders(n, k)

				
			

Output:

				
					1 mod 4 = 1
2 mod 4 = 2
3 mod 4 = 3
4 mod 4 = 0
5 mod 4 = 1
6 mod 4 = 2
7 mod 4 = 3

				
			
Handling ZeroDivisionError in Python

If the divisor (right operand) is zero, Python raises a ZeroDivisionError since division by zero is undefined. The example below shows how to handle this exception gracefully.

				
					# Example with exception handling for division by zero
num1 = 20
num2 = 0

try:
    print(num1, 'mod', num2, '=', num1 % num2, sep=" ")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed. Please use a non-zero divisor.")

				
			

Output:

				
					Error: Division by zero is not allowed. Please use a non-zero divisor.

				
			
Common Applications of the Modulo Operator in Python

1. Idnentifying Even or Odd Numbers

				
					# Check if a number is even or odd
num = 27
if num % 2 == 0:
    print("Even")
else:
    print("Odd")

				
			

Output:

				
					Odd

				
			

2. Cycling Through List Indices (e.g., Circular Buffer)

				
					# Cycling through indices with modulo
indices = [0, 1, 2, 3]
current_position = 6
index = current_position % len(indices)
print(indices[index])

				
			

Output:

				
					2

				
			

3. Checking Divisibility

				
					# Check if a number is divisible by another
num = 45
if num % 9 == 0:
    print("Divisible by 9")

				
			

Output:

				
					Divisible by 9

				
			
4. Time Calculations (e.g., Converting Minutes to Hours and Minutes)
				
					# Convert total minutes into hours and minutes
total_minutes = 150
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{hours} hours and {minutes} minutes")

				
			

Output:

				
					2 hours and 30 minutes

				
			
Modulo Operator and Negative Numbers

When working with negative numbers, the result of a % b in Python has the same sign as b.

				
					# Modulo with positive and negative values
result = 10 % -4
print(result)  # Output: -2

result = -10 % 4
print(result)  # Output: 2

				
			

Output:

				
					-2
2

				
			
Modulo with Floating-Point Numbers

Python’s modulo operator also works with floats and returns a remainder that may also be a float.

				
					# Example with floating-point values
result = 13.5 % 2.5
print(result)

				
			

Output:

				
					0.5

				
			

Python OR Operator

The OR operator in Python evaluates multiple boolean expressions and returns True if at least one expression is True. If all expressions evaluate to False, then it returns False.

Example: OR Operator with Boolean Expressions

				
					# Example with Boolean expressions
condition1 = 4 > 5
condition2 = 4 < 5

print('condition1:', condition1)
print('condition2:', condition2)

# OR operator
result = condition1 or condition2
print("OR operator result:", result)

				
			

Output:

				
					condition1: False
condition2: True
OR operator result: True

				
			

Example: Using Python OR Operator in an if Statement

				
					# OR operator in an if statement
def check_number(n):
    if n % 4 == 0 or n % 6 == 0:
        print(f"{n} is a multiple of 4 or 6")
    else:
        print(f"{n} is not a multiple of 4 or 6")

# Driver code
check_number(12)
check_number(5)
check_number(24)

				
			

Output:

				
					12 is a multiple of 4 or 6
5 is not a multiple of 4 or 6
24 is a multiple of 4 or 6

				
			
Python OR Operator – Short-Circuiting

The Python OR operator stops evaluating as soon as it encounters a True condition. This is known as short-circuiting, where it doesn’t check further expressions once a True is found.

				
					# Short circuiting with OR operator
def return_true():
    print("Executing return_true()")
    return True

def return_false():
    print("Executing return_false()")
    return False

# Case 1: First operand is True
case1 = return_true() or return_false()
print("Result of Case 1:", case1)
print()

# Case 2: Both operands are True
case2 = return_true() or return_true()
print("Result of Case 2:", case2)
print()

# Case 3: Both operands are False
case3 = return_false() or return_false()
print("Result of Case 3:", case3)
print()

# Case 4: First operand is False, second is True
case4 = return_false() or return_true()
print("Result of Case 4:", case4)

				
			

Output

				
					Executing return_true()
Result of Case 1: True

Executing return_true()
Result of Case 2: True

Executing return_false()
Executing return_false()
Result of Case 3: False

Executing return_false()
Executing return_true()
Result of Case 4: True

				
			

Walrus Operator in Python 3.8

The Walrus Operator in Python

The Walrus Operator (:=), introduced in Python 3.8, allows you to assign a value to a variable as part of an expression. This operator is particularly useful in cases where a value needs to be used repeatedly within the same expression, such as within loops or conditional statements, without having to calculate it multiple times.

Basic Syntax and Usage

The syntax for the Walrus Operator is variable := expression. This allows you to both evaluate and assign a value to variable within the context of an expression.

Example: Using the Walrus Operator in a while Loop

				
					numbers = [10, 20, 30, 40, 50]

while (n := len(numbers)) > 0:
    print(f"Remaining numbers: {numbers}, Length: {n}")
    numbers.pop()

				
			

Output:

				
					Remaining numbers: [10, 20, 30, 40, 50], Length: 5
Remaining numbers: [10, 20, 30, 40], Length: 4
Remaining numbers: [10, 20, 30], Length: 3
Remaining numbers: [10, 20], Length: 2
Remaining numbers: [10], Length: 1

				
			

Merging and Updating Dictionary Operators in Python

Traditional Method: Using update()

The update() method allows you to merge one dictionary into another. It modifies the first dictionary in-place by adding or updating keys from the second dictionary. However, it does not create a new dictionary, nor does it return any value.

Example: Merging Dictionaries with update()

				
					# Define two dictionaries
dict1 = {'x': 100, 'y': 200, 'z': 300}
dict2 = {'y': 250, 'z': 350, 'w': 400}

# Update dict1 with dict2 and return None
result = dict1.update(dict2)
print("Return value from update():", result)

# dict1 is modified
print("Updated dict1:", dict1)
print("Unchanged dict2:", dict2)

				
			

Output:

				
					Return value from update(): None
Updated dict1: {'x': 100, 'y': 250, 'z': 350, 'w': 400}
Unchanged dict2: {'y': 250, 'z': 350, 'w': 400}

				
			

Using ** to Merge Dictionaries

In Python, the ** operator can be used to unpack dictionaries, making it possible to merge multiple dictionaries in a single expression. This approach creates a new dictionary, leaving the original dictionaries unaltered.

Example: Merging Dictionaries Using ** Unpacking

				
					# Define two dictionaries
dict1 = {'p': 15, 'q': 25, 'r': 35}
dict2 = {'s': 45, 'r': 55, 'q': 65}

# Create a new dictionary by unpacking dict1 and dict2
merged_dict = {**dict1, **dict2}

print("Original dict1:", dict1)
print("Original dict2:", dict2)
print("Merged dictionary:", merged_dict)

				
			

Output:

				
					Original dict1: {'p': 15, 'q': 25, 'r': 35}
Original dict2: {'s': 45, 'r': 55, 'q': 65}
Merged dictionary: {'p': 15, 'q': 65, 'r': 55, 's': 45}

				
			

New Method in Python 3.9+: Using | and |= Operators

Python 3.9 introduces the dictionary merge (|) and update (|=) operators. The merge operator (|) creates a new dictionary by combining the contents of the two dictionaries, while the update operator (|=) modifies the dictionary on the left in place by adding or updating keys from the dictionary on the right.

Example: Merging with | and Updating with |=

				
					# Define two dictionaries
dict1 = {'m': 5, 'n': 10, 'o': 15}
dict2 = {'p': 20, 'o': 25, 'n': 30}

# Merge using |
merged_dict1 = dict1 | dict2
print("Merging dict1 with dict2 (dict1 | dict2):")
print(merged_dict1)

merged_dict2 = dict2 | dict1
print("\nMerging dict2 with dict1 (dict2 | dict1):")
print(merged_dict2)

# Update dict1 with dict2 using |=
dict1 |= dict2
print("\nUpdating dict1 with dict2 using |=:")
print("Updated dict1:", dict1)
print("Unchanged dict2:", dict2)

				
			

Output:

				
					Merging dict1 with dict2 (dict1 | dict2):
{'m': 5, 'n': 30, 'o': 25, 'p': 20}

Merging dict2 with dict1 (dict2 | dict1):
{'p': 20, 'o': 15, 'n': 10, 'm': 5}

Updating dict1 with dict2 using |=:
Updated dict1: {'m': 5, 'n': 30, 'o': 25, 'p': 20}
Unchanged dict2: {'p': 20, 'o': 25, 'n': 30}

				
			

Chaining comparison operators in Python

In programming, checking multiple conditions is common. Instead of writing separate conditions with logical operators, Python allows you to combine comparisons into a single expression through chaining. This feature simplifies expressions like:

				
					if a < b and b < c:
   {...}

				
			

In Python, you can simplify this with comparison chaining:

				
					if a < b < c:
    {...}

				
			

Python supports chaining comparisons using operators like >, <, ==, >=, <=, !=, is, is not, in, and not in.

Comparison chaining in Python follows typical mathematical notation, making it intuitive. For example, x < y <= z is equivalent to x < y and y <= z, but with a key difference: each expression is evaluated only once. So, if x < y is false, y and z won’t be evaluated, improving performance.

This chaining doesn’t imply comparisons between non-adjacent elements; for instance, a < b > c is valid and checks that a < b and b > c but does not relate a and c.

Example of Comparison Operator Chaining

				
					# Demonstrating chaining of comparison operators
x = 7
print(1 < x < 15)          # Checks if x is between 1 and 15
print(15 < x < 20)         # Checks if x is between 15 and 20
print(x < 15 < x * 2 < 200) # Checks multiple conditions on x
print(10 >= x <= 10)       # Checks if x is equal to or less than 10
print(7 == x > 4)          # Checks if x is both 7 and greater than 4

				
			

Output:

				
					True
False
True
True
True

				
			

Importance of Parentheses in Logical Expressions

When combining and and or with comparison chaining, parentheses are essential for clarifying precedence. Without them, expressions may not evaluate as expected, since and has higher precedence than or.

				
					p = 3
q = 7
r = 12

# Example with no parentheses
if p < q or q < r and r < p:
    print("This might not be printed as expected")

# Using parentheses to clarify precedence
if (p < q or q < r) and r < p:
    print("This will be printed as expected")

				
			

Output:

				
					This might not be printed as expected

				
			

Python Membership Operators

Membership operators check if a value is present in a sequence (e.g., strings, lists, dictionaries).

Membership Operators
OperatorDescriptionSyntax
inReturns True if the value exists in a sequence, else Falsevalue in sequence
not inReturns True if the value does not exist in a sequence, else Falsevalue not in sequence
Python in Operator

The in operator tests whether a character, element, or substring exists within a sequence, returning True if it’s found, and False otherwise.

Example :

				
					# Check if 'z' exists in a string (case-sensitive check)
'z' in 'PythonProgramming'
# Output: False

				
			
Python is not Operator

The is not operator returns True if variables refer to different memory locations.

Example:

				
					# Variables
num_a, num_b = 15, 15
list_a = [1, 2]
list_b = [1, 2]
list_c = list_a

# Testing identity
print(num_a is not num_b)    # False
print(list_a is not list_b)  # True
print(list_a is not list_c)  # False

				
			

Output:

				
					False
True
False