What are Operators in Python - Types of Operators in Python ( With Examples )

What are Operators in Python - Types of Operators in Python ( With Examples )

20 Jul 2024
Beginner
78.7K Views
22 min read

Python Operators: An Overview

Operators in Python Programming are the fundamental concepts that are important to know. These operators are needed to perform various operations in Python such as arithmetic calculations, logical evaluations, bitwise manipulations, etc. 

In this Python Tutorial, you will get to know about Python Operators, Types of Operators in Python with Example, and Precedence of Operators in Python. If you are new to Python and want to learn it from scratch, our Python Certification Training will help you with that.

What are Operators in Python?

In Python, operators are special symbols or keywords that carry out operations on values and python variablesThey serve as a basis for expressions, which are used to modify data and execute computations. Python contains several operators, each with its unique purpose.

Types of Python Operators

Python language supports various types of operators, which are:
  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Assignment Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

Types of Python Operators

Read More - 50 Python Interview Questions and Answers

1. Python Arithmetic Operators

  • Mathematical operations including addition, subtraction, multiplication, and division are commonly carried out using Python arithmetic operators.
  • They are compatible with integers, variables, and expressions.
  • In addition to the standard arithmetic operators, there are operators for modulus, exponentiation, and floor division.
OperatorNameExample
+Addition10 + 20 = 30
-Subtraction20 – 10 = 10
*Multiplication10 * 20 = 200
/Division20 / 10 = 2
%Modulus22 % 10 = 2
**Exponent4**2 = 16
//Floor Division9//2 = 4

Example of Python Arithmetic Operators in Python Compiler

     a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)

This code defines the two variables "a" and "b." It then applies several arithmetic operations to them (including addition, subtraction, multiplication, division, modulus, exponentiation, and floor division) and outputs the results.

Output

a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a % b : 1
a ** b : 16679880978201
a // b : 2

Read More - Python Developer Salary

2. Python Comparison Operators

OperatorNameExample
==Equal4 == 5 is not true.
!=Not Equal4 != 5 is true.
>Greater Than4 > 5 is not true
<Less Than4 < 5 is true
>=Greater than or Equal to4 >= 5 is not true.
<=Less than or Equal to4 <= 5 is true.

Example of Python Comparison Operators

        a = 4
b = 5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)

This code compares the values of python variables 'a' and 'b' and prints if they are equal, not equal, greater than, less than, more than or equal to, and less than or equal to each other.

Output

a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True

3. Python Assignment Operators

  • Python assignment operators are used to assign values to variables in Python.
  • The single equal symbol (=) is the most fundamental assignment operator.
  • It assigns the value on the operator's right side to the variable on the operator's left side.
Operator Name Example
=Assignment Operatora = 10
+=Addition Assignmenta += 5 (Same as a = a + 5)
-=Subtraction Assignmenta -= 5 (Same as a = a - 5)
*=Multiplication Assignmenta *= 5 (Same as a = a * 5)
/=Division Assignmenta /= 5 (Same as a = a / 5)
%=Remainder Assignmenta %= 5 (Same as a = a % 5)
**=Exponent Assignmenta **= 2 (Same as a = a ** 2)
//=Floor Division Assignmenta //= 3 (Same as a = a // 3)

Example of Python Assignment Operators

        # Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)

The Python assignment operators are shown in this code in the Python Editor. It begins with the value of 'a' equal to 10, and then goes through the steps of addition, subtraction, multiplication, division, remainder, exponentiation, and floor division, updating 'a' as necessary and outputting the results.

Output

a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0

4. Python Bitwise Operators

  • Python bitwise operators execute operations on individual bits of binary integers.
  • They work with integer binary representations, performing logical operations on each bit location.
  • Python includes various bitwise operators, such as AND (&), OR (|), NOT (), XOR (), left shift (), and right shift (>>).
Operator Name Example
&Binary ANDSets each bit to 1 if both bits are 1
|Binary ORSets each bit to 1 if one of the two bits is 1
^Binary XORSets each bit to 1 if only one of two bits is 1
~Binary Ones ComplementInverts all the bits
~Binary Ones ComplementInverts all the bits
<<Binary Left ShiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Binary Right ShiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Example of Python Bitwise Operators

        a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
# Binary AND
c = a & b # 12 = 0000 1100
print ("a & b : ", c)
# Binary OR
c = a | b # 61 = 0011 1101
print ("a | b : ", c)
# Binary XOR
c = a ^ b # 49 = 0011 0001
print ("a ^ b : ", c)
# Binary Ones Complement
c = ~a; # -61 = 1100 0011
print ("~a : ", c)
# Binary Left Shift
c = a << 2; # 240 = 1111 0000
print ("a << 2 : ", c)
# Binary Right Shift
c = a >> 2; # 15 = 0000 1111
print ("a >> 2 : ", c)

The binary representations of the numbers 'a and b' are subjected to bitwise operations in this code. It displays the results of binary AND, OR, XOR, Ones Complement, Left Shift, and Right Shift operations.

Output

a & b : 12
a | b : 61
a ^ b : 49
~a : -61
a >> 2 : 240
a >> 2 : 15

5. Python Logical Operators

  • Python logical operators are used to compose Boolean expressions and evaluate their truth values.
  • They are required for the creation of conditional statements as well as for managing the flow of execution in programs.
  • Python has three basic logical operators: AND, OR, and NOT.
Operator Description Example
and Logical ANDIf both of the operands are true then the condition becomes true.(a and b) is true.
or Logical ORIf any of the two operands is non-zero then the condition becomes true.(a or b) is true.
not Logical NOTUsed to reverse the logical state of its operandNot(a and b) is false.

Example of Python Logical Operators in Python Online Editor

          x = 5
y = 10
if x > 3 and y < 15:
  print("Both x and y are within the specified range")

The code assigns the values 5 and 10 to variables x and y. It determines whether x is larger than 3 and y is less than 15. If both conditions are met, it writes "Both x and y are within the specified range."

Output

Both x and y are within the specified range

6. Python Membership Operators

OperatorDescriptionExample
inEvaluates to true if it finds a variable in the specified sequence and false otherwise.x in y, here in results in a 1 if x is a member of sequence y.
not inEvaluates to true if it does not find a variable in the specified sequence and false otherwise.x not in y, here not in results in a 1 if x is not a member of sequence y.

Example of Python Membership Operators

        fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("Yes, banana is a fruit!")
else:
    print("No, banana is not a fruit!")

The code defines a list of fruits and tests to see if the word "banana" appears in the list. If it is, the message "Yes, banana is a fruit!" is displayed; otherwise, the message "No, banana is not a fruit!" is displayed.

Output

Yes, banana is a fruit!

7. Python Identity Operators

  • Python identity operators are used to compare two objects' memory addresses rather than their values.
  • If the two objects refer to the same memory address, they evaluate to True; otherwise, they evaluate to False.
  • Python includes two identity operators: the is and is not operators.
Operator Description Example
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwisex is y, here are results in 1 if id(x) equals id(y)
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwisex is not y, there are no results in 1 if id(x) is not equal to id(y).

Example of Python Identity Operators

        x = 10
y = 5
if x is y:
    print("x and y are the same object")
else:
    print("x and y are not the same object")

The code sets the variables x and y to 10 and 5, respectively. It then uses the is keyword to determine whether x and y relate to the same item in memory. If they are, it displays "x and y are the same object"; otherwise, it displays "x and y are not the same object."

Output

x and y are not the same object

Python Operators Precedence

Python Operator's Precedence can be explained by this given table,

Sr.No.OperatorDescription
1.**Exponentiation (raise to the power)
2.~ + -Complement, unary plus and minus (method names for the last two are +@ and -@)
3.* / % //Multiply, divide, modulo, and floor division
4.+ -Addition and subtraction
5.>> <<Right and left bitwise shift
6.&Bitwise 'AND'
7.^ |Bitwise exclusive `OR' and regular `OR'
8.<= < > >=Comparison operators
9.<> == !=Equality operators
10.= %= /= //= -= += *= **=Assignment operators
11.is is notIdentity operators
12in not inMembership operators
13.not or andLogical operators

Guidelines for using operators effectively

  • You must use parentheses to write more readable and clearer expressions.
  • Python allows for chaining operators, but using them in excess will only make the code more complex and difficult to read, so avoid them as much as possible.
  • Use names for variables that clearly describe the purpose of the operands.
  • Pay extra attention while using Membership and Identity operators.
  • Use Bitwise operators only when necessary as they can be a little complicated to use.
  • Test your code thoroughly to check if all the operators are working correctly or not.
Summary
In conclusion, we have learned the definition of the operator, including its usage, with the help of examples, Python Operators, types of operators in Python, Operators in Python, and the Precedence of Operators in Python. Additionally, if you're looking to validate your understanding of Python operators and enhance your programming skills, consider pursuing a Python Certification. Thanks for reading!

FAQs

A symbol or special character performing actions on one or more operands is called an operator in Python.

With Python lists, the operators + (concatenation), * (repetition), [] (indexing), and [:] (slicing) are often used.

In Python, there are seven fundamental operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulo), // (floor division), and ** (exponentiation).

Python is a high level programming language which comparatively simpler and readable. Operators in Python are certain symbols that are used in the python code to perform various operations on different values and variables.

There are many different types of operators in Python such as arithmetic operators, comparison operators, logical operators, bitwise operators, assignment operators, identity operators and membership operators.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this