Operators in Python

Operators are special symbols or keywords used to perform operations on variables and values. Python supports various types of operators to handle different operations.


1. Arithmetic Operators

Used for basic mathematical operations.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division5 / 2 = 2.5
%Modulus (Remainder)5 % 2 = 1
**Exponentiation (Power)5 ** 2 = 25
//Floor Division5 // 2 = 2

2. Comparison Operators

Used to compare values, returning True or False.

OperatorDescriptionExample
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater than or equal to5 >= 5 → True
<=Less than or equal to5 <= 3 → False

3. Logical Operators

Used to combine conditional statements.

OperatorDescriptionExample
andReturns True if both are true(5 > 3 and 2 < 4) → True
orReturns True if one is true(5 > 3 or 2 > 4) → True
notReverses the resultnot(5 > 3) → False

4. Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Assignx = 5
+=Add and assignx += 3 → x = 8
-=Subtract and assignx -= 2 → x = 6
*=Multiply and assignx *= 2 → x = 12
/=Divide and assignx /= 3 → x = 4
//=Floor divide and assignx //= 2 → x = 2
%=Modulus and assignx %= 2 → x = 0
**=Exponent and assignx **= 2 → x = 25

5. Bitwise Operators

Used to perform operations on binary numbers.

OperatorDescriptionExample
&AND5 & 3 → 1
``OR
^XOR5 ^ 3 → 6
~NOT~5 → -6
<<Left shift5 << 1 → 10
>>Right shift5 >> 1 → 2

6. Membership Operators

Used to test membership in a sequence like a list or string.

OperatorDescriptionExample
inReturns True if value is found"a" in "apple" → True
not inReturns True if value is not found"x" not in "apple" → True

7. Identity Operators

Used to compare memory locations of two objects.

OperatorDescriptionExample
isReturns True if same objectx is y → True
is notReturns True if different objectsx is not y → True

Examples:

# Arithmetic
a, b = 10, 3
print(a + b) # Output: 13
print(a % b) # Output: 1

# Comparison
print(a > b) # Output: True

# Logical
print(a > 5 and b < 5) # Output: True

# Membership
fruits = ["apple", "banana"]
print("apple" in fruits) # Output: True

# Identity
x = [1, 2, 3]
y = x
print(x is y) # Output: True

Understanding operators allows you to perform a wide range of operations and make your Python programs dynamic and functional.

CATEGORIES:

BASICS

Tags:

No responses yet

Leave a Reply

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