View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  • Home
  • Blog
  • Data Science
  • Operators in Python: A Beginner’s Guide to Arithmetic, Relational, Logical & More

Operators in Python: A Beginner’s Guide to Arithmetic, Relational, Logical & More

By Rohit Sharma

Updated on Jun 24, 2025 | 16 min read | 7.77K+ views

Share:

Did you know? With 92% of data professionals and 80% of AI developers preferring Python for its simplicity and efficiency, it’s the top choice for many industries. Python plays a central role in data science, AI, machine learning, automation, web development, finance, and scientific computing.

Operators in Python are special symbols or keywords that perform operations on variables and values, enabling you to implement everything from simple calculations to complex logic. 

Each plays a key role in Python, from arithmetic and comparison to bitwise, logical, and assignment operators. Understanding how and when to use them is essential for writing robust applications.

In this blog, we’ve explored the different types of operators in Python with practical examples to help solidify your learning and prepare you for real-world coding scenarios.

Looking to sharpen your Python programming skills further? Explore upGrad’s Software Engineering courses, designed with hands-on projects and mentorship to help you master core concepts like operators in Python, control flow, and beyond. Enroll today!

Understanding the Types of Operators in Python

Python supports various operator types, including arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators. Each type serves a distinct purpose and is vital in everyday programming tasks, whether building a calculator, managing user inputs, or processing large datasets.

This section breaks down each type of operator with examples, making it easier for beginners and experienced developers to grasp their syntax, functionality, and practical use cases.

Planning to enhance your Python programming skills and understand how operators drive core logic? The following guide simplifies the concept and sets you on a path to becoming a confident Python developer.

Here is a quick breakdown of the types of operators in Python and examples to help you understand how each works in practice.

Operator Type

Description

Example

Arithmetic Operators Perform basic mathematical operations a + b, a * b, a % b
Comparison Operators Compare two values and return a boolean result a > b, a == b, a != b
Assignment Operators Assign values to variables a = 5, a += 3
Logical Operators Combine conditional statements a > 3 and b < 10
Bitwise Operators Perform bit-level operations a & b, a << 2
Membership Operators Check if a value is present in a sequence 'x' in my_list
Identity Operators Compare the memory locations of two objects a is b, a is not b

Here’s a detailed breakdown of each operator type in Python with examples to illustrate their usage.

1. Arithmetic Operators in Python

Python arithmetic operators perform common mathematical calculations, such as addition, subtraction, multiplication, and division. They work with numerical data types such as integers and floats and are often used in variable assignments and expressions.

Python also provides additional arithmetic operations, such as modulus (to find remainders), exponentiation (power), and floor division (quotient without decimal).

Here are the commonly used arithmetic operators in Python, along with their descriptions and examples:

Operator

Name

Description

Example

Result

+ Addition Adds two operands 10 + 20 30
- Subtraction Subtracts the right operand from the left 20 - 10 10
* Multiplication Multiplies two operands 10 * 20 200
/ Division Divides the left operand by the right operand 20 / 10 2.0
% Modulus Returns remainder 22 % 10 2
** Exponentiation Raises the first operand to the power of the second 4 ** 2 16
// Floor Division Returns the quotient without remainder 9 // 2 4


Sample Code:

a = 21
b = 10
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)

Code Explanation:

  • a + b Adds 21 and 10 
  • a - b Subtracts 10 from 21 
  • a * b Multiply 21 by 10 
  • a / b Divides 21 by 10 
  • a % b Gets the remainder of 21 ÷ 10 
  • a ** b Raises 21 to the 10th power 
  • a // b Performs floor division (no decimals) 

Output:

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

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Start Your Coding Journey with upGrad’s Free Python Programming Course. Join the Learn Basic Python Programming course by upGrad to master core Python concepts with real-world projects and hands-on exercises. This beginner-friendly course will give you practical skills and a certification upon completion.

Also Read: Step-by-Step Guide to Learning Python for Data Science

2. Comparison Operators in Python

Python comparison operators are used to compare two values or expressions. They evaluate the relationship between the operands and return a Boolean value — either True or False. These operators are essential for decision-making in conditional statements, loops, and logic-based operations.

They work with numerical data types, strings, and even complex data structures like lists and tuples when comparison is required.

Here are the commonly used comparison operators in Python, along with their descriptions and examples:

Operator

Name

Description

Example

Result

== Equal to Returns True if both operands are equal 4 == 5 False
!= Not equal to Returns True if the operands are not equal 4 != 5 True
> Greater than Returns True if left is greater than right 4 > 5 False
< Less than Returns True if left is less than right 4 < 5 True
>= Greater than or equal Returns True if left >= right 4 >= 5 False
<= Less than or equal Returns True if left <= right 4 <= 5 True


Sample Code:

a = 4
b = 5

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)

Code Explanation:

  • a == b Checks if a is equal to b
  • a != b Checks if a is not equal to b
  • a > b Checks if a is greater than b
  • a < b Checks if a is less than b
  • a >= b Checks if a is greater than or equal to b
  • a <= b Checks if a is less than or equal to b

Output:

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

Ready to Strengthen Your Coding Foundation? Join upGrad’s Data Structures & Algorithms course today and gain the skills top tech companies demand. Learn quickly, solve real-world problems, and earn an industry-recognized certification.

Also Read: Techniques of Decision-Making: 15+ Tools & Methods for Success in 2025

3. Assignment Operators in Python

Assignment operators in Python assign values to variables. The simplest form is the equals sign (=), which assigns the value on the right to the variable on the left. Python also provides compound assignment operators that perform an operation and assignment in a single step, making your code more concise and readable.

These operators are handy for arithmetic updates to a variable and are widely used in loops, counters, and calculations.

Here are the commonly used assignment operators in Python, along with their descriptions and examples:

Operator

Name

Description

Example

Equivalent To

= Assignment Assigns value from right to left a = 10 -
+= Add and assign Adds and assigns a += 5 a = a + 5
-= Subtract and assign Subtracts and assigns a -= 5 a = a - 5
*= Multiply and assign Multiplies and assigns a *= 5 a = a * 5
/= Divide and assign Divides and assigns a /= 5 a = a / 5
%= Modulus and assign Computes modulus and assigns a %= 3 a = a % 3
**= Exponent and assign Raises to power and assigns a **= 2 a = a ** 2
//= Floor divide and assign Performs floor division and assigns a //= 3 a = a // 3


Sample Code:

a = 10

a += 5
print("a += 5:", a)

a -= 5
print("a -= 5:", a)

a *= 5
print("a *= 5:", a)

a /= 5
print("a /= 5:", a)

a %= 3
print("a %= 3:", a)

a **= 2
print("a **= 2:", a)

a //= 3
print("a //= 3:", a)

Code Explanation:

  • a = 10 Initializes the variable a with a value of 10
  • a += 5 Adds 5 to a
  • a -= 5 Subtracts 5 from a
  • a *= 5 Multiply a by 5 
  • a /= 5 Divides a by 5 
  • a %= 3 Computes the remainder of a divided by 3 
  • a **= 2 Raises a to the power of 2 
  • a //= 3 Performs floor division by 3 

Output:

a += 5: 15
a -= 5: 10
a *= 5: 50
a /= 5: 10.0
a %= 3: 1.0
a **= 2: 1.0
a //= 3: 0.0

4. Bitwise Operators in Python

Bitwise operators in Python allow you to perform operations at the binary level. They are particularly useful when dealing with low-level programming tasks, such as device drivers, encryption, graphics, or performance-optimized applications.

Each bitwise operation manipulates the bits of integers directly. Python converts numbers into binary form, performs the operation, and returns the result.

Here are the commonly used bitwise operators in Python with examples:

Operator

Name

Description

Example

& Bitwise AND Sets each bit to 1 if both bits are 1 a & b
` ` Bitwise OR Sets each bit to 1 if at least one bit is 1
^ Bitwise XOR Sets each bit to 1 only if one of the bits is 1 a ^ b
~ Bitwise NOT Inverts all the bits ~a
<< Left Shift Shifts bits left, adding 0s on the right a << 2
>> Right Shift Shifts bits right, removing bits on the right a >> 2


Sample Code:

a = 60  # 60 = 0011 1100
b = 13  # 13 = 0000 1101

print("a & b:", a & b)    # AND
print("a | b:", a | b)    # OR
print("a ^ b:", a ^ b)    # XOR
print("~a:", ~a)          # NOT
print("a << 2:", a << 2)  # Left Shift
print("a >> 2:", a >> 2)  # Right Shift

Code Explanation:

  • a & b Performs bitwise AND 
  • a | b Performs bitwise OR 
  • a ^ b Performs bitwise XOR 
  • ~a Performs bitwise NOT 
  • a << 2 Shifts a two bits left 
  • a >> 2 Shifts a two bits right 

Output:

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

Also Read: Comprehensive Guide to Binary Code: Basics, Uses, and Practical Examples

5. Logical Operators in Python

Logical Operators, also known as Boolean Operators, are used in Python to build expressions that evaluate to Boolean values (True or False). They are fundamental to creating control structures like if-elsewhile, and loops that make decisions based on multiple conditions.

Python includes three logical operators that help you combine conditions and control the flow of your program.

Here are the three leading logical operators in Python:

Operator

Description

Example

and Returns True if both statements are true (x > 3 and y < 15)
or Returns True if at least one statement is true (x > 3 or y > 20)
not Reverses the result: returns False if the result is true not(x > 3 and y < 15)

Sample Code:

x = 5
y = 10

# Logical AND
if x > 3 and y < 15:
    print("Both x and y are within the specified range")

# Logical OR
if x < 3 or y < 15:
    print("At least one condition is met")

# Logical NOT
if not(x < 3):
    print("x is not less than 3")

Code Explanation:

  • x > 3 and y < 15 Both conditions are true 
  • x < 3 or y < 15 The second condition is true
  • not(x < 3) Since x is not less than 3, the expression inside not is False, so not turns it into True.

Output:

Both x and y are within the specified range
At least one condition is met
x is not less than 3

Also Read: How to Use While Loop Syntax in Python: Examples and Uses

6. Membership Operators in Python

Membership operators test whether a value or variable is found in a sequence (such as a string, list, tuple, set, or dictionary). These operators return a Boolean value: True if the value is present and False otherwise.

Here are the membership operators in Python along with examples:

Operator

Description

Example

in Returns True if a value is found in a sequence 'a' in 'apple'
not in Returns True if a value is not in a sequence 'b' not in 'cat'

Sample Code:

my_list = [1, 2, 3, 4, 5]

print(3 in my_list)        # True: 3 is in the list
print(6 in my_list)        # False: 6 is not in the list
print(6 not in my_list)    # True: 6 is not in the list
print(2 not in my_list)    # False: 2 is in the list

Code Explanation:

  • 3 in my_list Checks if 3 is a member of my_list 
  • 6 in my_list 6 is not in the list 
  • 6 not in my_list 6 is not found 
  • 2 not in my_list 2 is found 

Output:

True
False
True
False

7. Identity Operators in Python

Identity operators compare the memory locations of two objects. They determine whether two variables refer to the same object (i.e., they are the same instance, not just equal in value).

These are especially useful when dealing with mutable types or checking if a variable is None.

Here are the identity operators in Python with examples:

Operator

Description

Example

is Returns True if both variables point to the same object a is b
is not Returns True if both variables do not point to the same object a is not b

Sample Code:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)       # True: b refers to the same object as a
print(a is c)       # False: c has the same content but is a different object
print(a == c)       # True: a and c have equal content
print(a is not c)   # True: a and c are not the same object

Code Explanation:

  • a is b Both variables point to the exact memory location
  • a is c Even though the contents are equal, they are different objects
  • a == c Compare values, and they're equal
  • a is not c Since a and c are not the same object

Output:

True
False
True
True

Also Read: Python Classes and Objects [With Examples]

upGrad’s Exclusive Data Science Webinar for you –

 

Python Operator Precedence

In Python, when an expression contains multiple operators, the order of evaluation is determined by operator precedence. Operators with higher precedence are evaluated before those with lower precedence. This concept helps Python correctly interpret complex expressions and ensures predictable outcomes.

For example, multiplication has a higher precedence than addition in the expression 3 + 4 * 2, so 4 * 2 is evaluated first, giving 3 + 8 = 11.

Understanding operator precedence is critical for writing accurate, bug-free expressions, especially in conditional logic, mathematical operations, and function calls.

Below is the standard operator precedence in Python, from highest to lowest:

Precedence

Operator(s)

Description

1 ** Exponentiation
2 ~+- Bitwise NOT, Unary plus, Unary minus
3 */%// Multiplication, Division, Modulo, Floor Division
4 +- Addition, Subtraction
5 >><< Bitwise Right Shift, Left Shift
6 & Bitwise AND
7 ^, ` `
8 <=<>>= Comparison Operators
9 ==!= Equality Operators
10 =+=-=, etc. Assignment Operators
11 isis not Identity Operators
12 innot in Membership Operators
13 notorand Logical Operators
Note: Operators in the same group (row) are evaluated left to right (left-associative), except **, which is right-associative.

What is Left-Associativity?

When an operator is left-associative, expressions with multiple operators of the same precedence are evaluated from left to right.

Example (Left-Associative Operators):

result = 10 - 5 - 2

Python evaluates this as:

(10 - 5) - 2 → 5 - 2 → 3

Code explanation: Subtraction (-) is a left-associative operator in a table; you can see that Python goes left to right.

What is Right-Associativity?

When an operator is right-associative, expressions with multiple operators of the same precedence are evaluated from right to left.

Example (Right-Associative Operator **):

result = 2 + 3 - 4 ** 2 ** 1
print(result)

Step-by-Step Evaluation:

1. Understand Operator Precedence:

  • ** has the highest precedence and is right-associative.
  • + and - have lower precedence and are left-associative.

So, exponentiation will be evaluated before addition or subtraction.

2. Evaluate Exponentiation (Right-to-Left):

4 ** 2 ** 1
→ 4 ** (2 ** 1) = 4 ** 2 = 16

3. Plug Back into the Expression:

result = 2 + 3 - 16

4. Evaluate Addition and Subtraction (Left-to-Right):

  • First 2 + 3 = 5
  • Then 5 - 16 = -11

Output:

-11

This demonstrates how different associativity rules impact the final result when multiple operators are involved in a single expression.

Sample Code of Associativity in Python:

x = 5
y = 10
z = 2

# Expression with multiple operators
result = x + y * z ** 2 > 30 and not (x == y)

print("Result of expression:", result)

Code Explanation: In this expression, multiple types of operators are used: arithmetic (+, *, **), comparison (> and ==), and logical (and, not). Python evaluates the expression based on operator precedence, which defines the order in which operations are performed.

  1. Exponentiation (**): z ** 2 
  2. Multiplication (*): y * 4 
  3. Addition (+): x + 40 
  4. Comparison (>): 45 > 30 
  5. Equality (==): x == y
  6. Logical NOT: not False 
  7. Logical AND: True and True 

Step-by-step Evaluation (with Reasons):

1. Exponentiation (**) has the highest precedence: Exponentiation is evaluated first.

z ** 2 → 2 ** 2 = 4

2. Multiplication (*) comes next: The result from the exponentiation is multiplied by y

y * 4 → 10 * 4 = 40

3. Addition (+) follows: The multiplication result is added to x.

x + 40 → 5 + 40 = 45

4. Comparison (>) is then evaluated: This checks if the result of the arithmetic expression is greater than 30.

45 > 30 → True

5. Inside the parentheses: Equality (==) comes next: This checks whether x and y are equal. The parentheses ensure this part is evaluated separately.

x == y → 5 == 10 → False

6. Logical NOT (not) is then applied: The not operator inverts the Boolean result of the equality check.

not False → True

7. Logical AND (and) is evaluated last: Since both conditions (45 > 30 and not (x == y)) are True, the final result is True.

True and True → True

How Can upGrad Help You Master Python and Ace Your Programming Journey?

Python operators form the foundation of your programs' logical, mathematical, and conditional operations. From arithmetic and assignment to logical, identity, and bitwise operations, each operator plays a crucial role in writing efficient, readable code. A clear understanding of these operator types helps master Python syntax and improves problem-solving and debugging skills.

Hands-on practice and real-world examples are key to mastering programming fundamentals. upGrad’s industry-relevant software development programs help you strengthen core Python concepts like operators, data structures, and control flow.

Here are some additional courses that can boost your programming journey and prepare you for real-world development:

Not sure how operators in Python are applied in real-world projects? Connect with upGrad’s expert counselors or drop by your nearest upGrad offline center to discover a personalized learning path aligned with your goals.

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

Reference: 
https://www.agileinfoways.com/blogs/python-in-it-industry-2025/

Frequently Asked Questions (FAQs)

1. I’m new to Python and confused about operator precedence. How do I know which operation gets evaluated first in a complex expression?

2. Can I overload operators like + or * in my own Python classes? How does that work?

3. Why do I get a TypeError when using arithmetic operators on lists or dictionaries in Python? Can’t I just add or subtract them?

4. How do identity operators like is differ from equality operators like == in real-world Python code?

5. I noticed Python allows a += b and a = a + b. Are they always the same, or is there a performance or behavior difference?

6. Why does my Python logical expression not return what I expect? I thought and and or returned Boolean values.

7. Can I use logical operators like and, or inside a list comprehension or lambda? What are the best practices?

8. I sometimes get negative numbers as output when using bitwise operators in Python. Why does ~a return a negative value?

9. I’m debugging a significant expression with many operators. Is there a practical way to test which part is causing unexpected output?

10. Are Python operators consistent with other languages like Java or JavaScript? Can switching cause mistakes?

11. I want to customize the behavior of logical or comparison operators in my class. Can I override those in Python?

Rohit Sharma

763 articles published

Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

17 Months

upGrad Logo

Certification

3 Months