Operators perform operations on variables and values. Python groups them into several types — below each type I give a short explanation plus runnable examples.

1. Arithmetic operators

Used with numeric values for basic math.

a = 7
b = 3

# Addition
print(a + b)   # 10

# Subtraction
print(a - b)   # 4

# Multiplication
print(a * b)   # 21

# Division (float)
print(a / b)   # 2.3333333333333335

# Modulus (remainder)
print(a % b)   # 1   (7 divided by 3 leaves remainder 1)

# Exponentiation
print(2 ** 3)  # 8   (2 to the power of 3)

# Floor division (integer quotient)
print(a // b)  # 2   (7 // 3 == 2)

2. Assignment operators

Used to assign values to variables; augmented forms modify the variable in place

x = 10     # simple assignment
x += 5     # equivalent to: x = x + 5
print(x)   # 15

x *= 2     # equivalent to: x = x * 2
print(x)   # 30

x -= 10    # x = x - 10
print(x)   # 20

x //= 3    # x = x // 3  (floor division assignment)
print(x)   # 6

x **= 2    # x = x ** 2  (exponentiation assignment)
print(x)   # 36

3. Comparison operators

Compare two values and return True or False.

print(5 == 5)   # True
print(5 != 3)   # True
print(4 > 7)    # False
print(4 < 7)    # True
print(5 >= 5)   # True
print(3 <= 2)   # False

4. Logical operators

Combine boolean expressions: and, or, not.

print((5 > 3) and (2 < 4))   # True  (both are True)
print((5 > 3) or (2 > 4))    # True  (one is True)
print(not (5 > 3))           # False (negates the expression)

5. Identity operators

Check whether two references point to the same object in memory: is, is not.

a = [1, 2, 3]
b = a             # b refers to the same list object
c = [1, 2, 3]     # c is a different list with same contents

print(a is b)     # True   (same object)
print(a is c)     # False  (different objects)
print(a == c)     # True   (contents equal)
print(a is not c) # True

is is about identity (memory location), == is about equality (value).

6. Membership operators

Test whether a value is present in a sequence: in, not in.

lst = [10, 20, 30]
print(20 in lst)      # True
print(5 not in lst)   # True

s = "hello"
print("ell" in s)     # True

7. Bitwise operators

Operate on the binary representation of integers (&, |, ^, ~, <<, >>). Examples for &, |, ^:

x = 5   # binary 0101
y = 3   # binary 0011

print(x & y)   # 1   (0101 & 0011 => 0001)
print(x | y)   # 7   (0101 | 0011 => 0111)
print(x ^ y)   # 6   (0101 ^ 0011 => 0110)

# Other bitwise ops:
print(~x)      # bitwise NOT (negation)
print(x << 1)  # left shift  (0101 << 1 => 1010 => 10)
print(x >> 1)  # right shift (0101 >> 1 => 0010 => 2)

Related posts:-

Total Page Visits: 21087 - Today Page Visits: 167

Leave a Reply