• 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 | 8.1K+ 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

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double 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

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

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?

You’re not alone. Operator precedence in Python can be tricky at first, especially when combining multiple types of operators like arithmetic, comparison, and logical ones. Python follows a strict hierarchy for evaluating expressions. For instance, exponentiation ** comes before multiplication *, which comes before addition +, and comparison operators come after arithmetic ones. Logical operators like and and or are evaluated at the end. To make your code easier to read and avoid surprises, you can always use parentheses () to explicitly control evaluation order. This prevents bugs and makes your logic crystal clear to other developers reading your code.

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

Yes, Python fully supports operator overloading through special methods. If you're defining a custom class and want the + operator to work with its instances, you can implement the __add__() method. Similarly, for *, implement __mul__(), and so on. This is especially useful when creating mathematical models, vectors, or data structures classes. For example, in a Vector class, __add__ could define how two vectors are added component-wise. Ensure the behavior is intuitive and consistent with the operator’s common use.

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?

Great question. Python enforces strict type rules for its built-in data structures. You can use + to concatenate lists or strings, but not with dictionaries or across incompatible types like lists and strings. Subtraction and division are not defined for lists or dictionaries at all. If you need to combine or manipulate collections element-wise, consider using zip(), list comprehensions, or NumPy arrays for numerical operations. Python is versatile, but it expects you to use the proper structure for the right task.

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

This is a critical distinction. The == operator checks if two variables have equal values, while the is operator checks if they reference the same object in memory. For example, two lists with the same elements will return True for == but False for is. Identity operators are mainly used when dealing with singleton objects like None or when you want to ensure two references point to the same instance, such as in caching or singleton patterns. Be cautious with is — it’s not a substitute for value comparison.

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

They might look the same, but there’s a subtle difference. a += b is an in-place operation if a is a mutable object like a list, meaning it modifies the object directly. On the other hand, a = a + b creates a new object and reassigns it to a. This has implications on performance and memory usage, especially in loops or large datasets. With immutable types like integers or strings, both versions effectively result in reassignment, but for mutable types, always think about whether you want to mutate the original object or not.

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

Python's logical operators return the actual object values, not just True or False. For example, a or b returns a if it’s truthy; otherwise, it returns b. Similarly, a and b return a if it's falsy; otherwise, they return b. This behavior can be powerful when used intentionally, like setting default values (result = user_input or "default"), but confusing if you expect strictly Boolean results. If you want an accurate Boolean return, explicitly cast the result using bool().

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

You can use logical operators inside list comprehensions and lambdas. They work well for filtering and conditional logic. For instance, [x for x in nums if x > 0 and x % 2 == 0] filters even positive numbers. In lambdas, use them for concise conditions: lambda x: x > 0 and x < 10. However, avoid writing overly complex expressions inside them — for better readability, break logic into named functions if the condition involves multiple operators.

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

The ~ operator performs a bitwise NOT operation, flipping all bits of an integer. In Python, integers are of arbitrary length and internally represented using two’s complement for negative numbers. So when you apply ~a, it effectively computes -a - 1. For example, ~5 becomes -6. This behavior surprises many developers coming from other languages with fixed-width integers. If you want a binary-safe bitmasking operation, mask results using & with an appropriate bitmask.

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

When facing a complex expression, break it into smaller parts and assign them to intermediate variables. This makes debugging easier and also improves readability and maintainability. For instance, instead of writing if a + b * c > d and not e == f:, split it into steps:

temp1 = b * c  
temp2 = a + temp1  
condition = temp2 > d and not e == f  

Now you can print each temp value or inspect it in a debugger. This modular approach is widely practiced in production-level code for better traceability.

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

There are similarities, but also subtle and important differences. For instance, == in Java compares primitives by value but references by identity. In Python, == always checks value equality, while is checks identity. Also, Python’s logical operators are andornot, while Java and JavaScript use &&||, and !. Python’s short-circuiting behavior and return of actual values in logical expressions can be surprising, too. So yes, switching between languages without understanding these nuances can lead to bugs.

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

Python allows you to override comparison operators using special methods like __eq__ for ==__lt__ for <, and so on. However, you cannot override logical operators like andor, or not directly. Python doesn't let you define __and__ or __or__ in the same intuitive way for logical operations. For custom boolean logic, you can define __bool__() to control how your object behaves in a Boolean context. For example, if my_obj: will call my_obj.__bool__() or fall back to __len__().

Rohit Sharma

834 articles published

Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...

Speak with Data Science Expert

+91

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

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

upGrad
new course

Certification

30 Weeks

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

17 Months