Operators in Python

In Python, an operator is a special symbol or keyword used to perform operations on one or more operands. Operators are fundamental to programming and are used to manipulate data and variables. They allow you to perform various types of operations, such as arithmetic calculations, comparisons, logical operations, and bitwise manipulations.

Types of Operators in Python

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, division, multiplication etc.

The following table shows all the arithmetic operators:

OperatorOperator NameDescriptionExample
+AdditionAdds two operands.5 + 3 results in 8
-SubtractionSubtracts the second operand from the first operand.5 - 3 results in 2
*MultiplicationMultiplies two operands.5 * 3 results in 15
/DivisionDivides the first operand by the second operand (float result).5 / 2 results in 2.5
//Floor DivisionDivides and returns the largest integer less than or equal to the result.5 // 2 results in 2
%ModulusReturns the remainder of the division.5 % 2 results in 1
**ExponentiationRaises the first operand to the power of the second operand.5 ** 2 results in 25

Example:

arithmetic_operators.py
# Addition
a = 10
b = 5
addition = a + b
print("Addition:", addition)  # Output: Addition: 15
 
# Subtraction
subtraction = a - b
print("Subtraction:", subtraction)  # Output: Subtraction: 5
 
# Multiplication
multiplication = a * b
print("Multiplication:", multiplication)  # Output: Multiplication: 50
 
# Division
division = a / b
print("Division:", division)  # Output: Division: 2.0
 
# Floor Division
floor_division = a // b
print("Floor Division:", floor_division)  # Output: Floor Division: 2
 
# Modulus
modulus = a % b
print("Modulus:", modulus)  # Output: Modulus: 0
 
# Exponentiation
exponentiation = a ** b
print("Exponentiation:", exponentiation)  # Output: Exponentiation: 100000

Assignment Operators

Assignment operators are used to assign values to variables. Python provides several types of assignment operators: simple assignment and compound (or shorthand) assignment operators.

Simple Assignment Operator

The simple assignment operator = assigns the value on the right-hand side to the variable on the left-hand side.

Syntax:

variable = value

Example:

x = 10      # Assigns the value 10 to variable x
name = "Eniv"  # Assigns the string "Eniv" to variable name

Compound Assignment Operators

Compound assignment operators combine an arithmetic operation with assignment. They modify the variable's value and then assign the result back to the variable. This can make the code more concise and easier to read.

Here are the common compound assignment operators:

OperatorOperator NameDescriptionExample
+=Addition AssignmentAdds the right operand to the left operand and assigns the result to the left operand.x += 3 (equivalent to x = x + 3)
-=Subtraction AssignmentSubtracts the right operand from the left operand and assigns the result to the left operand.x -= 3 (equivalent to x = x - 3)
*=Multiplication AssignmentMultiplies the left operand by the right operand and assigns the result to the left operand.x *= 3 (equivalent to x = x * 3)
/=Division AssignmentDivides the left operand by the right operand and assigns the result to the left operand.x /= 2 (equivalent to x = x / 2)
//=Floor Division AssignmentDivides the left operand by the right operand using floor division and assigns the result to the left operand.x //= 2 (equivalent to x = x // 2)
%=Modulus AssignmentApplies modulus operation and assigns the result to the left operand.x %= 2 (equivalent to x = x % 2)
**=Exponentiation AssignmentRaises the left operand to the power of the right operand and assigns the result to the left operand.x **= 2 (equivalent to x = x ** 2)

Example:

assignment_operators.py
# Basic assignment
x = 10
print("Initial value of x:", x)  # Output: Initial value of x: 10
 
# Addition assignment
x += 5
print("After x += 5, value of x:", x)  # Output: After x += 5, value of x: 15
 
# Subtraction assignment
x -= 3
print("After x -= 3, value of x:", x)  # Output: After x -= 3, value of x: 12
 
# Multiplication assignment
x *= 2
print("After x *= 2, value of x:", x)  # Output: After x *= 2, value of x: 24
 
# Division assignment
x /= 4
print("After x /= 4, value of x:", x)  # Output: After x /= 4, value of x: 6.0
 
# Floor division assignment
x //= 2
print("After x //= 2, value of x:", x)  # Output: After x //= 2, value of x: 3.0
 
# Modulus assignment
x %= 2
print("After x %= 2, value of x:", x)  # Output: After x %= 2, value of x: 1.0
 
# Exponentiation assignment
x **= 3
print("After x **= 3, value of x:", x)  # Output: After x **= 3, value of x: 1.0

Python does not support the ++ (increment) and -- (decrement) operators that are found in languages like C++, Java, or JavaScript.

Comparison Operators

Comparison operators in Python are used to compare values and return a Boolean result (True or False). These operators are essential for control flow and making decisions in your code. The operands can be numbers, strings, or boolean values. Strings are compared letter by letter using their ASCII values. For instance, 'E' is less than 'S' because the ASCII value of 'E' (69) is less than the ASCII value of 'S' (83).

The following table shows all the comparison operators:

OperatorOperator NameDescriptionExample
==Equal toChecks if two operands are equal.5 == 5 results in True
!=Not equal toChecks if two operands are not equal.5 != 3 results in True
>Greater thanChecks if the first operand is greater than the second operand.5 > 3 results in True
<Less thanChecks if the first operand is less than the second operand.5 < 3 results in False
>=Greater than or equal toChecks if the first operand is greater than or equal to the second operand.5 >= 5 results in True
<=Less than or equal toChecks if the first operand is less than or equal to the second operand.5 <= 3 results in False

Example:

comparison_operators.py
# Equality Operator
print(10 == 10)   # Output: True
print(10 == 20)   # Output: False
 
# Inequality Operator
print(10 != 20)   # Output: True
print(10 != 10)   # Output: False
 
# Greater Than Operator
print(10 > 5)     # Output: True
print(5 > 10)     # Output: False
 
# Less Than Operator
print(5 < 10)     # Output: True
print(10 < 5)     # Output: False
 
# Greater Than or Equal To Operator
print(10 >= 10)   # Output: True
print(10 >= 5)    # Output: True
print(5 >= 10)    # Output: False
 
# Less Than or Equal To Operator
print(5 <= 10)    # Output: True
print(10 <= 5)    # Output: False
print(10 <= 10)   # Output: True

Don't confuse the equality operator (==) with the assignment operator (=).

  • The equality operator (==) is used to compare two values. It checks if the values are the same and returns True if they are, and False otherwise.

    Example:

    x = 5
    y = 5
    result = (x == y)  # Compares if x is equal to y
    # result is True because x and y both have the value 5
  • The assignment operator (=) is used to assign a value to a variable. It sets the value on the right side to the variable on the left side.

    Example:

    x = 5   # Assigns the value 5 to the variable x
    y = 10  # Assigns the value 10 to the variable y

In summary, x == y checks if x is equal to y, while x = y assigns the value of y to x.

Logical Operators

In Python, logical operators are used to combine multiple conditions together and evaluate them as a single boolean expression. There are three types of logical operators in Python: and, or, and not. The and operator returns True if both conditions it is evaluating are true, otherwise it returns False.

Here is list of logical operators:

OperatorOperator NameDescriptionExample
andLogical ANDReturns True if both operands are true.True and False results in False
orLogical ORReturns True if at least one of the operands is true.True or False results in True
notLogical NOTReturns True if the operand is false.not True results in False

Example:

and Operator

The and operator returns True if both operands are true. If either operand is false, it returns False.

Example:

x = 10
y = 20
 
# Both conditions must be true
result = (x > 5) and (y < 30)  # True
print(result)  # Output: True
 
result = (x > 15) and (y < 30)  # False (x > 15 is False)
print(result)  # Output: False

or Operator

The or operator returns True if at least one of the operands is true. It returns False only if both operands are false.

Example:

x = 10
y = 20
 
# At least one condition must be true
result = (x > 5) or (y < 15)  # True
print(result)  # Output: True
 
result = (x < 5) or (y < 15)  # False (both conditions are False)
print(result)  # Output: False

not Operator

The not operator negates the boolean value of the operand. It returns True if the operand is False, and False if the operand is True.

Example:

x = 10
 
# Negates the condition
result = not (x > 5)  # False (x > 5 is True, so not True is False)
print(result)  # Output: False
 
result = not (x < 5)  # True (x < 5 is False, so not False is True)
print(result)  # Output: True

Bitwise Operators

Bitwise operators in Python are used to perform operations at the bit level of integer values. These operators work on binary representations of numbers, performing bit-by-bit operations. A sequence consisting of ones and zeroes is known as binary. The smallest amount of information that you can store in a computer is known as a bit. A bit is represented as either 0 or 1.

Here is list of bitwise operators:

OperatorOperator NameDescriptionExample
&Bitwise ANDPerforms bitwise AND operation between two integers.5 & 3 results in 1
|Bitwise ORPerforms bitwise OR operation between two integers.5 | 3 results in 7
^Bitwise XORPerforms bitwise XOR operation between two integers.5 ^ 3 results in 6
~Bitwise NOTPerforms bitwise NOT operation, inverts all bits.~5 results in -6
<<Bitwise Left ShiftShifts the bits of the first operand to the left by the number of positions specified by the second operand.5 << 1 results in 10
>>Bitwise Right ShiftShifts the bits of the first operand to the right by the number of positions specified by the second operand.5 >> 1 results in 2

Bitwise AND (&)

The bitwise AND operator compares each bit of its two operands. If both bits are 1, the corresponding result bit is set to 1. Otherwise, it is set to 0.

Example:

a = 60          # Binary: 0011 1100
b = 13          # Binary: 0000 1101
result = a & b  # Binary: 0000 1100, Decimal: 12
print(result)   # Output: 12

Bitwise OR (|)

The bitwise OR operator compares each bit of its two operands. If at least one of the bits is 1, the corresponding result bit is set to 1. Otherwise, it is set to 0.

Example:

a = 60          # Binary: 0011 1100
b = 13          # Binary: 0000 1101
result = a | b  # Binary: 0011 1101, Decimal: 61
print(result)   # Output: 61

Bitwise XOR (^)

The bitwise XOR (exclusive OR) operator compares each bit of its two operands. If exactly one of the bits is 1, the corresponding result bit is set to 1. Otherwise, it is set to 0.

Example:

a = 60          # Binary: 0011 1100
b = 13          # Binary: 0000 1101
result = a ^ b  # Binary: 0011 0001, Decimal: 49
print(result)   # Output: 49

Bitwise NOT (~)

The bitwise NOT operator is a unary operator that inverts all the bits of its operand. It performs a bitwise negation. In Python, it returns the two's complement of the number.

Example:

a = 60          # Binary: 0011 1100
result = ~a     # Binary: 1100 0011, Decimal: -61 (in two's complement form)
print(result)   # Output: -61

Bitwise Left Shift (<<)

The left shift operator shifts the bits of its operand to the left by the number of positions specified. The vacant positions on the right are filled with 0.

Example:

a = 60          # Binary: 0011 1100
result = a << 2 # Binary: 1111 0000, Decimal: 240
print(result)   # Output: 240

Bitwise Right Shift (>>)

The right shift operator shifts the bits of its operand to the right by the number of positions specified. The vacant positions on the left are filled based on the sign bit (0 for positive numbers, 1 for negative numbers in two's complement).

Example:

a = 60          # Binary: 0011 1100
result = a >> 2 # Binary: 0000 1111, Decimal: 15
print(result)   # Output: 15

Precedence and Associativity

In Python, operators have a specific precedence and associativity that determine the order in which operations are performed in an expression.

Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before those with lower precedence. Here's a list of Python operators, ordered by their precedence from highest to lowest:

OperatorDescription
Parentheses ()Used to group expressions and override default precedence.
Exponentiation **Example: 2 ** 3 results in 8.
Unary Plus and Minus, Bitwise NOT +x, -x, ~xUnary plus (+) and minus (-) are used for positive and negative values respectively. Bitwise NOT (~) inverts all the bits of its operand.
Multiplication, Division, Floor Division, Modulus *, /, //, %Multiplication (*), Division (/), Floor Division (//), and Modulus (%) are evaluated left to right.
Addition and Subtraction +, -Addition (+) and subtraction (-) are evaluated left to right.
Bitwise Shift Operators <<, >>Left shift (<<) and right shift (>>) are evaluated left to right.
Bitwise AND &Bitwise AND is evaluated.
Bitwise XOR ^Bitwise XOR is evaluated.
Bitwise OR |Bitwise OR is evaluated.
Comparison Operators ==, !=, >, <, >=, <=Comparison operators are evaluated.
Logical NOT notLogical NOT (not) has higher precedence than the logical AND and OR operators.
Logical AND andLogical AND (and) is evaluated.
Logical OR orLogical OR (or) is evaluated.
Conditional Expressions if-elseConditional expressions have the lowest precedence.
Assignment Operators =, +=, -=, *=, /=, etc.Assignment and other compound assignment operators are evaluated.
Expressions separated by commas ,Used in tuples, function arguments, etc.

Operator Associativity

Operator associativity determines the order in which operators of the same precedence are evaluated. Most operators in Python are left-associative, meaning they are evaluated from left to right. Here’s a summary of associativity for different types of operators:

  1. Left-Associative: Most operators, including arithmetic (+, -, *, /), bitwise operators (&, |), and comparison operators (==, <, >). They are evaluated from left to right.

  2. Right-Associative: Exponentiation (**) and assignment operators (=, +=, -=, etc.) are right-associative. This means expressions like a = b = c are evaluated as a = (b = c).

  3. Non-Associative: Operators such as comparison operators (==, >, <) do not have associativity, meaning expressions involving these operators are evaluated based on precedence alone.

Examples:

Here's how precedence and associativity affect the evaluation of an expression:

operators.py
# Example 1: Exponentiation has higher precedence than multiplication
result = 2 * 3 ** 2
# 3 ** 2 is evaluated first, giving 9, then 2 * 9 is evaluated
print(result)  # Output: 18
 
# Example 2: Multiplication and division are left-associative
result = 10 / 2 * 5
# 10 / 2 is evaluated first, giving 5.0, then 5.0 * 5 is evaluated
print(result)  # Output: 25.0
 
# Example 3: Assignment is right-associative
x = y = 10
# y = 10 is evaluated first, then x = 10
print(x, y)  # Output: 10 10
 
# Example 4: Logical operators and their precedence
result = True or False and False
# False and False is evaluated first (result is False), then True or False is evaluated (result is True)
print(result)  # Output: True
How's article quality?

Last updated on -

Page Contents