Operators In Python

Introduction to Python Operators

Python operators are special symbols used to perform operations on variables and values. They help developers perform calculations, compare values, evaluate conditions, and manipulate data efficiently. Understanding Python operators is essential because they are used in almost every Python program. In this guide, you will learn the different types of Python operators, their syntax, examples, and practical applications.

Why Are Python Operators Important?

Python operators make coding easier and more efficient.

Benefits of Python Operators:

  • Perform mathematical calculations quickly.
  • Compare values and conditions.
  • Simplify decision-making logic.
  • Improve code readability.
  • Reduce the number of lines of code.

Example:

a = 10
b = 20

print(a + b)

Output:

30

Types of Operators

Operator TypeSymbolsCharacteristics
Arithmetic Operators+, -, *, /, //, %, **Perform basic mathematical operations
Assignment Operators=, +=, -=, *=, /=, //=, %=Assign values and perform operations on variables.
Relationship Operators==, !=, >, <, >=, <=Compare values and return a boolean result
Logical Operatorsand, or, notConstruct large conditions by combining Boolean values
Membership Operatorsin, not inCheck the given value present in the sequences
Identity Operatorsis, is notCheck for object identity (memory location address)
Bitwise Operators&, |, ^, ~,<<,>>Perform operations at the bit level
Ternary Operatorx = true_value if cond else false_valueIf the condition is True, then true_value will be considered else false_value will be considered.

Note: Python doesn’t support the — and ++ operators, unlike in C and Java.

Arithmetic Operators In Python

  • Arithmetic Operators in Python are used to do mathematical operations on numeric values.
  • They work with integers and decimal numbers and return numeric results.

Example:

a = 10
b = 5
print('Addition : ',a + b)
print('Subtraction : ',a - b)
print('Multiplication : ',a * b)
print('Division : ',a / b)
print('Floor Division : ',a // b)
print('Modulus : ',a % b)
print('Modulus : ',2 % 0)
print('Exponentiation : ',a ** b)

Output:

Addition : 15
Subtraction : 5
Multiplication : 50
Division : 2.0
Floor Division : 2
Modulus : 0
ZeroDivisionError: modulo by zero
Exponentiation : 100000

Assignment Operators

Assign values and perform operations on variables.

x = 10
x += 5  # Addition assignment: x = x + 5 -> 15
x -= 2  # Subtraction assignment: x = x - 2 -> 13
x *= 3  # Multiplication assignment: x = x * 3 -> 39
x /= 3  # Division assignment: x = x / 3 -> 13.0

Relational Operators In Python

  • These operators are used to compare two values.
  • These operators return two possible outcomes when we compare values: True or False.
  • By using these operators, we can construct simple conditions.

Assume that,
            a = 13
            b = 5

OperatorExampleResult
a>bTRUE
>=a>=bTRUE
a<bFALSE
<=a<=bFALSE
==a==bFALSE
!=a!=bTRUE

Example:

x = 10
y = 20
print('Equality or equal:',x == y)
print('Inequality or not equal:',x != y)
print('Greater than:',x > y)
print('Less than:',x < y)
print('Greater than or equal to:',x >= y)
print('Less than or equal to:',x <= y)

Output:

Equality or equal: False
Inequality or not equal: True
Greater than: False
Less than: True
Greater than or equal to: False
Less than or equal to: True

Logical operators

  • In Python, there are three logical operators:,
    • and: If both arguments are True, then the only result is True
    • or: If at least one argument is True, then the result is True
    • not: complement (opposite of actual result)
  • Logical operators help build compound conditions.
  • A compound condition is a combination of two or more simple conditions.
  • Each simple condition yields a Boolean result; finally, the compound condition evaluates to True or False.

Example 1:

a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output:

False
True
False

Example 2:

a = 10
b = 20
c = 30
print((a>b) and (b>c))
print((a<b) and (b<c))
print((a>b) or (b>c))

Output:

False
True
True

Membership operators

  • Membership operators help to check whether an object is present in a collection (sequence). (It may be string, list, set, tuple, range, or dict)
  • There are two membership operators,
    • in
    • not in
  • ‘in’ operator returns True if the element is found in the sequences, or else False
  • ‘not in’ operator returns True if the element is not found in the sequences or else False

Example:

lst = [10, 20, 30, 40, 50]
print(30 in lst)
print(60 not in lst)

Output:

True
True

Identity operators (is, is not)

  • These operators compare the memory locations (address) of two values.
  • Using the id() function to check the address of every element.

Example:

x=26
y=26
print(id(x))
print(id(y))

Output:

1570989024
1570989024

is operator:

  • X is Y returns True : if both X and Y have the same object.
  • X is Y returns False :  if both X and Y do not have the same object.

is not operator:

  • X is not Y returns True : if both A and B do not have the same object.
  • X is not Y returns False : if both A and B have the same object.

Example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b)
print(a is c)
print(a is not c)

Output:

True
False
True

Bitwise Operators

  • Bitwise operators can be applied to int and boolean data types only.
  • Applying bitwise operators to other data types will result in error.
OperatorDescription
&If both bits are 1 then only the result is 1 otherwise the result is 0
|If at least one bit is 1 then the result is 1 otherwise the result is 0
^If bits are different then only the result is 1 otherwise the result is 0
~bitwise complement operator i.e 1 is 0 and 0 is 1
>> Bitwise Left shift Operator
<< Bitwise Right shift Operator

Example 1:

print(5&6) # valid
print(11.5 & 5.6) # TypeError: unsupported operand type(s) for &: 'float' and 'float'
print(True & True) # valid

Example 2:

a = 10  # 1010 in binary
b = 4   # 0100 in binary
print(a & b)
print(a | b)
print(a ^ b)
print(~a)

Output:

0 (0000) # Bitwise AND
14 (1110) # Bitwise OR
14 (1110) # Bitwise XOR
-11 (inverted bits) # Bitwise NOT

Ternary Operator

Syntax: x = true_value if cond else false_value

If the condition is True then true_value will be used or else false_value will be considered.

Example 1:

a,b = 100,200
y = 300 if a<b else 400
print(y)

Output:

300

Example 2: Program for minimum of 3 numbers

a,b,c=10,20,30
min=(a if a<b and a<c else b) if b<c else c
print(min)

Output:

10

Common Mistakes While Using Python Operators

Using = Instead of ==

Incorrect:

if age = 18:

Correct:

if age == 18:

Dividing by Zero

num = 10 / 0

This generates:

ZeroDivisionError

Confusing is and ==

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

print(a == b)
print(a is b)

Understanding these mistakes helps avoid bugs in Python programs.

Conclusion

Python operators are fundamental building blocks of Python programming. They allow developers to perform calculations, compare values, evaluate conditions, and manipulate data efficiently. By understanding arithmetic, comparison, logical, assignment, membership, identity, bitwise, and ternary operators, you can write cleaner and more effective Python code. Mastering Python operators is an important step toward becoming a skilled Python developer.

Knowledge Check

Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices

Frequently Asked Questions

What are Python Operators?

Python operators are special symbols that perform operations on variables and values.

How many types of operators are available in Python?

Python provides arithmetic, assignment, comparison, logical, membership, identity, bitwise, and ternary operators.

What is the difference between == and is in Python?

The == operator compares values, whereas the is operator compares object identities.

What are arithmetic operators in Python?

Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, division, modulus, and exponentiation.

Which operator has the highest precedence in Python?

Parentheses have the highest precedence and are evaluated first.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *