View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Python Operators: Types, Syntax, and Implementation Guide

Updated on 20/05/20252,107 Views

If you've ever written even a single line of code in Python, chances are you've already used python operators without even realizing it. Whether you're adding two numbers, comparing values, or checking conditions, python operators are always at work behind the scenes. They're the building blocks of decision-making and calculations in any Python program. 

In this blog, we're going to walk you through everything you need to know about python operators, from the basic arithmetic ones to the slightly trickier bitwise and identity operators. Whether you're a beginner trying to understand how things work or an intermediate coder brushing up your skills, this guide is your one-stop solution. However, before we start, you should brush up your Python data types learning. 

And to make it even easier, each code snippet comes with comments, expected output, and a brief explanation. Learning code here, will assuredly help you easily understand any of the top-rated software development course

What are Python Operators?

Before we get into the different types, let's first understand what python operators really are.

Python operators are special symbols or keywords that perform operations on variables and values. In everyday Python programming, you’ll use these operators to do things like:

  • Add or subtract numbers
  • Compare two values
  • Combine multiple conditions
  • Assign values to variables
  • Perform operations at the bit level

Think of python operators as tools in your coding toolbox—they help you build logic and manipulate data efficiently. Just like a calculator has buttons for `+`, `-`, `*`, and `/`, Python has its own set of operators to make coding intuitive and powerful.

Fast-pace your career growth with the following full-stack development courses: 

Here's a simple example:

#Calculating her total marks
maths = 85
science = 90

# Using the + operator to find the total
total_marks = maths + science

print("Total Marks:", total_marks)

Output:

Total Marks: 175

Explanation:

In this example, the `+` sign is an arithmetic operator. It takes two variables—`maths` and `science`—and adds their values. Simple, right?

Throughout this blog, we’ll explore each category of python operators in detail, backed by practical code examples. Additionally, numerous developers get confused between operators and variables. To cut that clutter out, you should explore our articles about variables in Python

Types of Python Operators

Python offers a variety of operators, each designed to perform a specific kind of operation. To make things easier to understand, we've broken them down into the following major types:

  • Arithmetic Python Operators: For basic math operations like addition and division.
  • Comparison Python Operators:  For comparing values like greater than, less than, or equal to.
  • Logical Python Operators: For combining multiple conditions using AND, OR, and NOT.
  • Bitwise Python Operators: For low-level binary operations.
  • Assignment Python Operators: For assigning values to variables with shorthand notations.
  • Identity and Membership Python Operators: For checking object identity and membership in sequences.
  • Operator Precedence and Associativity: For understanding which operations Python evaluates first.

Each of these types plays a crucial role in writing efficient, readable, and logical Python code.

Also explore our detailed tutorial about Global Variable in Python!

Quick Overview Table:

Operator Type

Example Symbols

Use Case Example

Arithmetic

+, -, *, /

marks + bonus

Comparison

==, !=, <, >

age >= 18

Logical

and, or, not

is_student and is_adult

Bitwise

&, `

, ^, ~`

Assignment

=, +=, -=

x += 5

Identity

is, is not

a is b

Membership

in, not in

'a' in 'Rahul'

Each of these python operators will be covered in detail in the upcoming sections with practical examples.

Arithmetic Python Operators

Arithmetic operations are some of the most common tasks in any programming language, and Python makes it easy with its intuitive arithmetic python operators. These operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and more.

Here’s a list of the main arithmetic python operators:

Operator

Symbol

Description

Example

Addition

+

Adds two operands

a + b

Subtraction

-

Subtracts second from first

a - b

Multiplication

*

Multiplies operands

a * b

Division

/

Divides first by second

a / b

Modulus

%

Remainder of division

a % b

Exponentiation

**

Raises first to the power of second

a ** b

Floor Division

//

Division with result rounded down

a // b

Let’s walk through each of these with examples.

Example: Basic Arithmetic with Marks

# Exam scores in two subjects
maths = 88
english = 92

# Addition: Total score
total = maths + english  # 88 + 92 = 180

# Subtraction: Score difference
difference = english - maths  # 92 - 88 = 4

# Multiplication: Hypothetical scaling
scaled_score = maths * 2  # 88 * 2 = 176

# Division: Average score
average = total / 2  # 180 / 2 = 90.0

# Modulus: Remainder when total is divided by 7
remainder = total % 7  # 180 % 7 = 5

# Exponentiation: Square of maths score
square = maths ** 2  # 88 ** 2 = 7744

# Floor Division: Rounded down average
floor_div = total // 2  # 180 // 2 = 90

# Displaying all results
print("Total:", total)
print("Difference:", difference)
print("Scaled Score:", scaled_score)
print("Average:", average)
print("Remainder:", remainder)
print("Square of Maths:", square)
print("Floor Division of Total:", floor_div)

Output:

Total: 180

Difference: 4

Scaled Score: 176

Average: 90.0

Remainder: 5

Square of Maths: 7744

Floor Division of Total: 90

Explanation:

In this example, we used various arithmetic python operators to perform calculations based on Rahul’s marks. From basic addition and subtraction to more advanced operations like exponentiation and floor division, these operators help manage numeric data with ease.

Whether you're developing a billing system, analyzing scores, or doing data science, understanding these python operators is essential. Once you understand these operators, you’ll be a step-forward to leverage all advantages of Python programming. 

Comparison Python Operators

Comparison operators, also known as relational operators, are used to compare two values or variables. These python operators return a Boolean value—either True or False—based on whether the comparison condition is met.

Comparison operators are critical in control flow (like if, while, and for statements) because they help the program make decisions.

List of Comparison Python Operators

Operator

Symbol

Description

Example

Equal to

==

Checks if values are equal

a == b

Not equal to

!=

Checks if values are not equal

a != b

Greater than

>

Checks if left is greater

a > b

Less than

<

Checks if left is smaller

a < b

Greater than or equal to

>=

Checks if left is greater or equal

a >= b

Less than or equal to

<=

Checks if left is smaller or equal

a <= b

Explore our article on Inheritance in Python to develop advanced-level programs. 

Example: Checking Admission Eligibility

# Rajat's age and minimum required age for college
rajat_age = 19
required_age = 18

# Using comparison operators to check conditions
is_eligible = rajat_age >= required_age  # True
is_minor = rajat_age < 18  # False
exact_match = rajat_age == required_age  # False
not_equal = rajat_age != required_age  # True

# Displaying results
print("Is Rajat eligible for admission?", is_eligible)
print("Is Rajat still a minor?", is_minor)
print("Is Rajat exactly the required age?", exact_match)
print("Is Rajat's age not equal to required?", not_equal)

Output:

Is Rajat eligible for admission? True

Is Rajat still a minor? False

Is Rajat exactly the required age? False

Is Rajat's age not equal to required? True

Explanation:

Here, we used several comparison python operators to check Rajat’s age against a required threshold. These comparisons form the basis for many decision-making scenarios, like eligibility checks, access control, and conditional logic in programs.

Whether you're building a login system or filtering data, understanding how python operators compare values is crucial.

Logical Python Operators

Once you've started comparing values, the next logical step (pun intended) is combining those comparisons. That’s where logical python operators come in. These operators help you evaluate multiple conditions at once, returning True or False based on the overall logic.

Logical operators are especially important in decision-making, form validations, and loops. By learning all these concepts, you’ll clear your path to become a Python developer with exceptional skills. 

List of Logical Python Operators

Operator

Keyword

Description

Example

AND

and

Returns True if both conditions are true

a > 10 and b < 20

OR

or

Returns True if at least one is true

a > 10 or b < 20

NOT

not

Reverses the result: True becomes False

not(a > 10)

Example: College Admission Based on Marks and Age

# Shradha's details
age = 18
marks = 75

# Admission criteria: must be at least 18 and have 70+ marks
is_age_eligible = age >= 18
has_good_marks = marks >= 70

# Using logical operators to evaluate overall eligibility
eligible_for_admission = is_age_eligible and has_good_marks  # True
either_condition = is_age_eligible or has_good_marks  # True
not_eligible = not eligible_for_admission  # False

# Displaying the logical evaluations
print("Is Shradha eligible for admission?", eligible_for_admission)
print("Is she eligible based on either age or marks?", either_condition)
print("Is she not eligible?", not_eligible)

Output:

Is Shradha eligible for admission? True

Is she eligible based on either age or marks? True

Is she not eligible? False

Explanation:

In this example, we used all three logical python operators: and, or, and not. This allowed us to build more complex logic from simple comparison statements. These operators are essential when working with multiple criteria in any decision-making code.

As you continue building Python applications, you'll frequently combine comparison python operators with logical python operators to handle real-world scenarios effectively. 

Do explore Memory Management in Python to build efficient programs. 

Bitwise Python Operators

Bitwise operations are a bit more advanced, but extremely powerful when you’re working at a lower level of data processing—like cryptography, image processing, or network programming. Bitwise python operators work directly with binary digits (bits) of integers.

Instead of evaluating whole numbers or logic, these python operators compare bits using binary logic.

List of Bitwise Python Operators

Operator

Symbol

Description

Example

AND

&

Sets each bit to 1 if both bits are 1

a & b

OR

`

`

Sets each bit to 1 if one of two is 1

XOR

^

Sets each bit to 1 if only one is 1

a ^ b

NOT

~

Inverts all the bits

~a

Left Shift

<<

Shifts bits left (adds zeros to right)

a << 1

Right Shift

>>

Shifts bits right (removes rightmost bits)

a >> 1

Example: Bitwise Operations on Age and ID

# Rajan's binary ID and age values
id_number = 10       # In binary: 1010
age = 4              # In binary: 0100

# Bitwise AND
bitwise_and = id_number & age  # 1010 & 0100 = 0000

# Bitwise OR
bitwise_or = id_number | age  # 1010 | 0100 = 1110

# Bitwise XOR
bitwise_xor = id_number ^ age  # 1010 ^ 0100 = 1110

# Bitwise NOT
bitwise_not = ~id_number  # ~1010 = -1011 (2's complement in Python)

# Left Shift
left_shift = id_number << 1  # 1010 becomes 10100 = 20

# Right Shift
right_shift = id_number >> 1  # 1010 becomes 0101 = 5

# Display results
print("Bitwise AND:", bitwise_and)
print("Bitwise OR:", bitwise_or)
print("Bitwise XOR:", bitwise_xor)
print("Bitwise NOT:", bitwise_not)
print("Left Shift:", left_shift)
print("Right Shift:", right_shift)

Output:

Bitwise AND: 0

Bitwise OR: 14

Bitwise XOR: 14

Bitwise NOT: -11

Left Shift: 20

Right Shift: 5

Explanation:

Bitwise operations can seem intimidating at first, but they become powerful tools once you understand them. Here, Rajan's id_number and age were used in several bitwise python operators to perform binary-level operations. These are rarely used in simple applications but are indispensable in technical fields where performance and memory optimization matter.

Remember: These python operators only work on integers and their binary representations.

Do explore Frameworks in Python to add next-gen functionalities in your applications. 

Assignment Python Operators

Assignment operators in Python do more than just assign values to variables. They also provide shorthand notations to perform operations and assignments in a single line. This makes your code cleaner and more concise.

These assignment python operators are incredibly useful when updating the value of a variable based on its current value.

List of Assignment Python Operators

Operator

Description

Example

=

Assigns value

a = 5

+=

Adds and assigns

a += 5 (same as a = a + 5)

-=

Subtracts and assigns

a -= 3

*=

Multiplies and assigns

a *= 2

/=

Divides and assigns

a /= 4

%=

Modulus and assigns

a %= 2

**=

Exponentiation and assigns

a **= 2

//=

Floor division and assigns

a //= 3

&=, `

=, ^=, >>=, <<=`

Bitwise updates

Example: Priya Managing Her Wallet Balance

# Initial balance
wallet = 1000

# Priya buys books
wallet -= 300  # wallet = wallet - 300

# She earns from tutoring
wallet += 500  # wallet = wallet + 500

# She invests part of it
wallet *= 1.1  # wallet = wallet * 1.1 (10% return)

# She donates a small amount
wallet /= 2  # wallet = wallet / 2

# Floor division to round off
wallet //= 1  # wallet = wallet // 1

print("Final wallet balance:", wallet)

Output:

Final wallet balance: 605.0

Explanation:

In this example, Priya starts with ₹1000 and goes through a series of transactions. Each step uses a different assignment python operator to update her balance. These operators simplify arithmetic expressions by combining them with assignment logic in a clean, readable way.

Once you're familiar with them, you'll find these python operators not only save time but also improve the clarity of your code.

Must read about Speech Recognition in Python to create AI-enabled applications. 

Identity Python Operators and Membership Operators

While arithmetic, logical, and bitwise operations handle data, identity and membership operators help in working with objects and collections. These python operators are especially useful when dealing with lists, strings, or object references.

Let’s look at both types:

Identity Python Operators

Identity operators are used to check whether two variables refer to the same object in memory—not just equal in value, but actually the same object.

Operator

Description

Example

is

Returns True if both refer to same object

a is b

is not

Returns True if they do not refer to same object

a is not b

Example: Comparing Object Identity

# Two different lists with the same contents
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1  # list3 points to the same object as list1

# Identity checks
print("list1 is list2:", list1 is list2)        # False
print("list1 == list2:", list1 == list2)        # True (values are equal)
print("list1 is list3:", list1 is list3)        # True

Output:

list1 is list2: False

list1 == list2: True

list1 is list3: True

Explanation:

list1 and list2 have the same values but are stored at different memory locations, so list1 is list2 is False. list3 is just another name for list1, so list1 is list3 is True. Identity python operators are commonly used when you need to ensure two references are pointing to the same object.

Do explore Merge Sort in Python to gain industry-level development knowledge. 

Membership Python Operators

Membership operators are used to check whether a value or variable is part of a sequence (like a list, tuple, string, or dictionary).

Operator

Description

Example

in

Returns True if value exists

'a' in 'Rajan'

not in

Returns True if value does not exist

'x' not in list

Example: Checking Elements in Collections

# Rajan’s registered course list
courses = ['Python', 'Data Science', 'AI']

# Membership tests
print("Is 'Python' in Rajan's courses?", 'Python' in courses)      # True
print("Is 'Java' not in Rajan's courses?", 'Java' not in courses)  # True

# Checking character in string
name = "Rajan"
print("'a' in name:", 'a' in name)         # True
print("'x' not in name:", 'x' not in name) # True

Output:

Is 'Python' in Rajan's courses? True

Is 'Java' not in Rajan's courses? True

'a' in name: True

'x' not in name: True

Explanation:

Membership python operators are incredibly handy for filtering, searching, and validating data in lists, strings, and other iterable types. They let you check if a value is present (or absent) without writing complex loops.

Together, identity and membership operators expand the utility of python operators, especially when working with objects and collections.

Precedence and Associativity of Operators in Python

In Python, operator precedence determines the order in which operators are evaluated in an expression. Understanding this is crucial to ensure that your code produces the correct result.

Additionally, associativity defines the direction in which operators of the same precedence level are evaluated. By default, most operators have left-to-right associativity, but some operators, like exponentiation, evaluate right-to-left.

Operator Precedence

When you write an expression with multiple operators, Python follows a set of rules to decide which operator to apply first. The higher the precedence, the earlier the operator is applied.

Here’s a summary of the python operator precedence (from highest to lowest):

Operator Type

Operator

Precedence Order

Parentheses

()

1st

Exponentiation

**

2nd

Unary +, Unary -

+x, -x

3rd

Multiplication, Division, Modulus

*, /, %, //

4th

Addition, Subtraction

+, -

5th

Comparison Operators

==, !=, <, >, <=, >=

6th

Logical AND

and

7th

Logical OR

or

8th

Assignment

=, +=, -=

9th

Example: Operator Precedence in Action

# Example using multiple operators
x = 5
y = 10
z = 2
result = x + y * z ** 2  # Exponentiation, multiplication, addition

# Order of operations:
# 1. z ** 2 = 2 ** 2 = 4
# 2. y * 4 = 10 * 4 = 40
# 3. x + 40 = 5 + 40 = 45

print("Result:", result)  # Output will be 45

Output:

Result: 45

Explanation:

In this example, the exponentiation (z ** 2) is evaluated first because it has the highest precedence. Then, the multiplication (y * 4) is performed, followed by the addition (x + 40).

Operator Associativity

Most operators in Python follow left-to-right associativity, meaning they are evaluated from left to right. For example:

# Left-to-right evaluation
result = 5 - 3 + 2  # (5 - 3) + 2 = 4
However, exponentiation (**) is right-to-left associative. This means that expressions like 2 ** 3 ** 2 are evaluated from right to left, as 2 ** (3 ** 2):
# Right-to-left evaluation
result = 2 ** 3 ** 2  # 2 ** (3 ** 2) = 2 ** 9 = 512

Output:

Result: 512

Explanation:

In the case of exponentiation, 3 ** 2 is evaluated first, giving 9, and then 2 ** 9 is calculated, resulting in 512.

Importance of Parentheses

When in doubt about precedence, use parentheses () to make the order of operations explicit. Parentheses have the highest precedence in Python and ensure that the expression inside is evaluated first, overriding default precedence rules.

# Parentheses change the order of evaluation
result = (x + y) * z  # (5 + 10) * 2 = 15 * 2 = 30

Output:

Result: 30

Explanation:

In this case, parentheses are used to force addition to happen before multiplication, giving a different result from the previous example.

Conclusion 

In this blog, we have explored the different types of Python operators that are essential for performing various operations on data. From arithmetic and logical operations to comparison and bitwise manipulations, python operators form the foundation of decision-making and complex computations in Python programming.

Key Takeaways:

  • Python operators are powerful tools that allow us to perform mathematical calculations, compare values, and make logical decisions.
  • Understanding operator precedence and associativity ensures that expressions are evaluated in the correct order, preventing logical errors in your code.
  • Bitwise, membership, and identity operators add another layer of flexibility, allowing us to work with data at the binary level and handle complex data structures like lists, strings, and objects.
  • By practicing Python operators through hands-on coding examples, you can enhance your problem-solving skills and write cleaner, more efficient Python code.

FAQs

1. What is the difference between `=` and `==` in Python?

In Python, `=` is the assignment operator, used to assign values to variables. For example, `x = 10` assigns 10 to the variable `x`. On the other hand, `==` is the equality operator, used to compare two values. It returns `True` if the values are equal and `False` otherwise.

2. How can I check if two variables point to the same object in Python?

You can use the identity operator `is` to check if two variables point to the same object in memory. For example, `a is b` will return `True` if `a` and `b` refer to the same object, and `False` if they are different objects, even if they have the same value.

3. What are the common arithmetic operators in Python?

Common arithmetic operators in Python include `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `//` (floor division), `%` (modulus), and `**` (exponentiation). These operators perform basic mathematical calculations on numbers, both integers and floats.

4. What is the purpose of the `not` operator in Python?

The `not` operator is a logical operator that reverses the boolean value of an expression. If the expression is `True`, `not` changes it to `False`, and vice versa. It’s commonly used in conditional statements to check for the negation of a condition, such as `if not x`.

5. Can I use multiple Python operators in one expression?

Yes, you can combine multiple Python operators in a single expression, but operator precedence determines the order in which they are evaluated. Parentheses `()` can be used to override the default precedence and ensure that certain operations are performed first, making complex expressions clearer and more predictable.

6. What is the difference between `and` and `or` in Python?

In Python, `and` and `or` are logical operators used to combine multiple conditions. The `and` operator returns `True` only if both conditions are `True`, while `or` returns `True` if at least one condition is `True`. These operators are commonly used in `if` statements to check multiple conditions.

7. How do I perform bitwise operations in Python?

Bitwise operations in Python are performed using operators like `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), `<<` (left shift), and `>>` (right shift). These operators work at the binary level and are typically used for tasks such as low-level data manipulation or optimization in specific use cases like cryptography.

8. How do Python assignment operators like `+=` work?

Python assignment operators like `+=` are shorthand operators that combine an operation with assignment. For example, `x += 5` is equivalent to `x = x + 5`. These operators allow you to perform operations and update the variable in a more concise way, saving lines of code and improving readability.

9. What does `is not` do in Python?

In Python, `is not` is the negation of the `is` operator, used to check if two variables do not refer to the same object in memory. For example, `a is not b` returns `True` if `a` and `b` are different objects, even if they have the same value.

10. How do I check membership in a Python sequence?

You can use the `in` operator to check if a value exists in a sequence like a list, tuple, or string. For example, `5 in [1, 2, 3, 4, 5]` returns `True`. To check if a value is not in a sequence, use the `not in` operator, such as `6 not in [1, 2, 3, 4, 5]`.

11. What is the precedence of Python operators?

Python operators follow a specific order of precedence. For example, arithmetic operators like `*` and `/` have higher precedence than `+` and `-`, and comparison operators like `==` have lower precedence than arithmetic ones. Using parentheses can help override the default precedence and ensure the correct order of evaluation in complex expressions.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.