Python Operators Tutorial with Examples

In Python, operators are the symbols utilized to execute specific actions on various values and variables. These values and variables are referred to as operands, which the operator acts upon. Operators are essential building blocks for constructing logic within a program in a specific programming language.

Types of Python Operators

Different types of Operators used in Python are as follows:

  • Arithmetic Operators
  • Comparison Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Now, we will examine the various operators utilized in Python in the subsequent sections.

1. Arithmetic Operators

In Python, arithmetic operators are utilized on pairs of operands to execute fundamental mathematical computations such as addition, subtraction, multiplication, and division. Python provides various arithmetic operators, which include the following: the '+' operator for performing addition, the '-' operator for subtraction, the '' operator for multiplication, the '/' operator for division, the '%' operator for calculating the modulus, the '*' operator for exponentiation, and the '//' operator for floor division.

Let us examine the subsequent table of arithmetic operators for an in-depth discussion.

S. No. Operator Syntax Description
1 + (Addition) r = a + b This operator is used to add two operands. For example, if a = 15, b = 10 => a + b = 15 + 10 = 25
2 - (Subtraction) r = a - b This operator is used to subtract the second operand from the first operand. If the first operand is less than the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 20 - 5 = 15
3 / (divide) r = a / b This operator returns the quotient after dividing the first operand by the second operand. For example, if a = 15, b = 4 => a / b = 15 / 4 = 3.75
4 * (Multiplication) r = a * b This operator is used to multiply one operand with the other. For example, if a = 20, b = 4 => a b = 20 4 = 80
5 % (reminder) r = a % b This operator returns the reminder after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a % b = 20 % 10 = 0
6 ** (Exponent) r = a ** b As this operator calculates the first operand's power to the second operand, it is an exponent operator. For example, if a = 2, b = 3 => ab = 23 = 2^3 = 222 = 8
7 // (Floor division) r = a // b This operator provides the quotient's floor value, which is obtained by dividing the two operands. For example, if a = 15, b = 4 => a // b = 15 // 4 = 3

Now we give code examples of arithmetic operators in Python. The code is given below -

Example

Example

a = 46    # Initializing the value of a

b = 4     # Initializing the value of b

print("For a =", a, "and b =", b,"\nCalculate the following:")

# printing different results

print('1. Addition of two numbers: a + b =', a + b)

print('2. Subtraction of two numbers: a - b =', a - b)

print('3. Multiplication of two numbers: a * b =', a * b)

print('4. Division of two numbers: a / b =', a / b)

print('5. Floor division of two numbers: a // b =',a // b)

print('6. Reminder of two numbers: a mod b =', a % b)

print('7. Exponent of two numbers: a ^ b =',a ** b)

Output:

Output

For a = 46 and b = 4

Calculate the following:

1. Addition of two numbers: a + b = 50

2. Subtraction of two numbers: a - b = 42

3. Multiplication of two numbers: a * b = 184

4. Division of two numbers: a / b = 11.5

5. Floor division of two numbers: a // b = 11

6. Reminder of two numbers: a mod b = 2

7. Exponent of two numbers: a ^ b = 4477456

2. Comparison Operators

In Python, comparison operators serve the primary function of evaluating two values or variables (known as operands) and yielding a Boolean result, which can be either True or False based on the evaluation. Python offers several types of comparison operators, such as '==', '!=', '<=', '>=', and '<', and '>'.

Let’s examine the subsequent table that illustrates comparison operators for a comprehensive understanding.

S. No. Operator Syntax Description
1 == a == b Equal to: If the value of two operands is equal, then the condition becomes true.
2 != a != b Not Equal to: If the value of two operands is not equal, then the condition becomes true.
3 >== a >= b Greater than or Equal to: The condition is met if the first operand is greater than or equal to the second operand.
5 > a > b Greater than: If the first operand is greater than the second operand, then the condition becomes true.
6 >=>=', and '+= a = a + b Add AND: This operator adds the operand on the right side to the operand on the left side and assigns the resultant value to the left operand. For example, if a = 15, b = 20 => a += b will be equal to a = a + b and therefore, a = 15 + 20 => a = 35
3 -= a -= b => a = a - b Subtract AND: This operator subtracts the operand on the right side from the operand on the left side and assigns the resultant value to the left operand. For example, if a = 47, b = 32 => a -= b will be equal to a = a - b and therefore, a = 47 - 32 => a = 15
4 *= a = b => a = a b Multiply AND: This operator multiplies the operand on the right side with the operand on the left side and assigns the resultant value to the left operand. For example, if a = 12, b = 4 => a = b will be equal to a = a b and therefore, a = 12 * 4 => a = 48
5 /= a /= b => a = a / b Divide AND: This operator divides the operand on the left side with the operand on the right side and assign the resultant value to the left operand. For example, if a = 15, b = 2 => a /= b will be equal to a = a / b and therefore, a = 15 / 2 => a = 7.5
6 %= a %= b => a = a % b Modulus AND: This operator calculates the modulus of using the left-side and right-side operands and assigns the resultant value to the left operand. For example, if a = 20, b = 10 => a %= b will be equal to a = a % b and therefore, a = 20 % 10 => a = 0
7 **= a = b => a = a b Exponent AND: This operator calculates the exponent value using the operands on both side and assign the resultant value to the left operand. For example, if a = 2, b = 3 => a = b will be equal to a = a b and therefore, a = 2 ** 3 = 8
8 //= a //= b => a = a // b Divide (floor) AND: This operator divides the operand on the left side with the operand on the right side and assign the resultant floor value to the left operand. For example, if a = 15, b = 2 => a //= b will be equal to a = a // b and therefore, a = 15 // 2 => a = 7

Example

Example

a = 34         # Initialize the value of a

b = 6          # Initialize the value of b

# printing the different results

print('a += b:', a + b)

print('a -= b:', a - b)

print('a *= b:', a * b)

print('a /= b:', a / b)

print('a %= b:', a % b)

print('a **= b:', a ** b)

print('a //= b:', a // b)

Output:

Next, we will compile the aforementioned code using Python, and upon successful compilation, we will execute it. The resulting output is displayed below -

Example

a += b: 40

a -= b: 28

a *= b: 204

a /= b: 5.666666666666667

a %= b: 4

a **= b: 1544804416

a //= b: 5

3. Bitwise Operators

The values of the two operands are handled on a bit-by-bit basis by the bitwise operators. Python provides a variety of Bitwise operators, including bitwise OR (|), bitwise AND (&), bitwise XOR (^), bitwise negation (~), and the Left shift (<<), and Right shift (>>).

Let us examine the subsequent table of bitwise operators for a comprehensive discussion.

S. No. Operator Syntax Description
1 & a & b Bitwise AND:1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is copied.
2 a b Bitwise OR:The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
3 ^ a ^ b Bitwise XOR:If the two bits are different, the outcome bit will be 1, else it will be 0.
4 ~ ~a Bitwise NOT:The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice versa.
5 <a>> a >> Bitwise Right Shift:The left operand is moved right by the number of bits present in the right operand.

Example

Example

a = 7          # initializing the value of a

b = 8          # initializing the value of b

# printing different results

print('a & b :', a & b)

print('a | b :', a | b)

print('a ^ b :', a ^ b)

print('~a :', ~a)

print('a << b :', a << b)

print('a >> b :', a >> b)

Output:

Output

a & b : 0

a | b : 15

a ^ b : 15

~a : -8

a << b : 1792

a >> b : 0

5. Logical Operators

Evaluating expressions to guide decisions generally involves the use of logical operators. In Python, there are several kinds of logical operators available, including and, or, and not. Regarding the logical AND operator, if the initial operand is 0, the outcome does not rely on the second operand. Conversely, with the logical OR operator, if the first operand is 1, the result is independent of the second operand.

Let us examine the table below that illustrates the logical operators utilized in Python for a comprehensive explanation.

S. No. Operator Syntax Description
1 and a and b Logical AND:The condition will also be true if the expression is true. If the two expressions a and b are the same, then a and b both must be true.
2 or a or b Logical OR:The condition will be true if one of the phrases is true. If a and b are the two expressions, then either a or b must be true to make the condition true.
3 not not a Logical NOT:If an expression a is true, then not (a) will be false and vice versa.

Example

Example

a = 7          # initializing the value of a

# printing different results

print("For a = 7, checking whether the following conditions are True or False:")

print('\"a > 5 and a < 7\" =>', a > 5 and a < 7)

print('\"a > 5 or a < 7\" =>', a > 5 or a < 7)

print('\"not (a > 5 and a < 7)\" =>', not(a > 5 and a < 7))

Output:

Output

For a = 7, checking whether the following conditions are True or False:

"a > 5 and a < 7" => False

"a > 5 or a < 7" => True

"not (a > 5 and a < 7)" => True

6. Membership Operators

In Python, we can check if a value is a member of a data structure by utilizing the membership operators provided by the language. The outcome is considered true when the value or variable exists within the sequence (such as a list, tuple, or dictionary); if not, it yields false.

S. No. Operator Description
1 in If the first operand (value or variable) is present in the second operand (sequence), it is evaluated to be true. Sequence can either be a list, tuple, or dictionary
2 not in If the first operand (value or variable) is not present in the second operand (sequence), the evaluation is true. Sequence can either be a list, tuple, or dictionary

Example

Example

# initializing a list

myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]

# initializing x and y with some values

x = 31

y = 28

# printing the given list

print("Given List:", myList)

# checking if x is present in the list or not

if (x not in myList):

    print("x =", x,"is NOT present in the given list.")

else:

    print("x =", x,"is present in the given list.")

# checking if y is present in the list or not

if (y in myList):

    print("y =", y,"is present in the given list.")

else:

    print("y =", y,"is NOT present in the given list.")

Output:

Output

Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]

x = 31 is NOT present in the given list.

y = 28 is present in the given list.

7. Identity Operators

Python provides two identity operators, namely is and is not, which are utilized to determine whether two values occupy the same memory location. It is important to note that two variables may be equal in value but do not necessarily imply that they are identical.

S. No. Operator Description
1 is If the references on both sides point to the same object, it is determined to be true.
2 is not If the references on both sides do not point at the same object, it is determined to be true.

Example

Example

# initializing two variables a and b

a = ["Rose", "Lotus"]

b = ["Rose", "Lotus"]

# initializing a variable c and storing the value of a in c

c = a

# printing the different results

print("a is c => ", a is c)

print("a is not c => ", a is not c)

print("a is b => ", a is b)

print("a is not b => ", a is not b)

print("a == b => ", a == b)

print("a != b => ", a != b)

Output:

Output

a is c =>  True

a is not c =>  False

a is b =>  False

a is not b =>  True

a == b =>  True

a != b =>  False

Operator Precedence

The sequence in which operators are evaluated is essential for comprehension, as it indicates the priority of each operator during execution. Presented below is a compilation of the precedence tables for Python operators.

S. No. perator Description
1 ** Overall other operators employed in the expression, the exponent operator is given precedence.
2 ~, +, - the minus, unary plus, and negation.
3 *, /, %, // the division of the floor, the modules, the division, and the multiplication.
4 +, - Binary plus, and minus
5 >>, <, >, >= Comparison operators (less than, less than equal to, greater than, greater then equal to).
9 <>, ==, != Equality operators.
10 =, %=, /=, //=, -=, +=,=, *= Assignment operators
11 is, is not Identity operators
12 in, not in Membership operators
13 not, or, and Logical operators

Conclusion

This article has examined all the various operators available in Python. We have provided a detailed overview of each operator individually, including examples and corresponding outputs to enhance comprehension. Additionally, we have discussed operator precedence to clarify which operator takes priority in expressions. Operators in Python are crucial for performing calculations.

Python Operators FAQs

1. What are operators in Python?

In Python, operators are the symbols utilized to execute particular operations on various values and variables. These values and variables are referred to as operands, which the operator acts upon.

2. What are the types of operators in Python?

There are different types of Operators used in Python, as follows:

  • Arithmetic Operators
  • Comparison Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators
  • 3. What is the difference between / and // in Python?

  • /: This operator divides the numbers but gives the result in floating point.
  • //: This operator divides the number and gives the integer result.

/: This operator performs division on the numbers and returns the result as a floating-point value.

To illustrate the distinction between '/' and '//', let’s consider a practical example:

Example:

Example

#Entering the number

number = int(input("Enter a number: "))

print("The above number divided by 3 is: ")

#using / operator

print("Using '/' operator: ", number/3)

#using // operator

print("Using '//' operator: ", number//3)

Output:

Output

Enter a number: 10

The above number divided by 3 is:

Using '/' operator:  3.3333333333333335

Using '//' operator:  3

4. What is the difference between == and is?

The == operator is utilized to determine if two values are equivalent.

The is operator is utilized to determine whether two variables point to the identical object in memory.

Example:

Example

a = [1, 2]

b = [1, 2]

#using the '==' operator

print(a == b)

#using the 'is' operator

print(a is b)

Output:

Output

True

False

5. What is the difference between AND, OR, and NOT?

  • AND: The AND operator returns True if both conditions are evaluated to be true.
  • OR: The OR operator returns True if at least one condition is true.
  • NOT: The NOT operator reverses the condition.

Example:

Example

x, y = True, False

print(x and y)

print(x or y)

print(not x)

Output:

Output

False

True

False

Input Required

This code uses input(). Please provide values below: