Operators in Python

Operators in Python are special symbols used to perform operations on variables and values. Python supports several types of operators, each designed for a specific kind of operation.

1. Arithmetic Operators:

These operators are used to perform mathematical operations:

Python
x = 10
y = 3

print(x + y)  # Output: 13
print(x - y)  # Output: 7
print(x * y)  # Output: 30
print(x / y)  # Output: 3.3333333333333335
print(x % y)  # Output: 1
print(x ** y)  # Output: 1000
print(x // y)  # Output: 3

2. Comparison Operators:

Comparison operators are used to compare two values. They return a Boolean result:

Python
x = 10
y = 20

print(x == y)  # Output: False
print(x != y)  # Output: True
print(x > y)  # Output: False
print(x < y)  # Output: True
print(x >= y)  # Output: False
print(x <= y)  # Output: True

3. Logical Operators:

Logical operators are used to combine conditional statements:

Python
x = 10
y = 5
z = 20

print(x > y and z > x)  # Output: True
print(x > y or x > z)  # Output: True
print(not(x > y))  # Output: False

4. Assignment Operators:

Assignment operators are used to assign values to variables. They can also combine with arithmetic operators:

Python
x = 10

x += 5  # x = x + 5
print(x)  # Output: 15

x *= 2  # x = x * 2
print(x)  # Output: 30

x //= 3  # x = x // 3
print(x)  # Output: 10

5. Bitwise Operators:

Bitwise operators are used to compare binary numbers:

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

print(x & y)  # Output: 1 (0001 in binary)
print(x | y)  # Output: 7 (0111 in binary)
print(x ^ y)  # Output: 6 (0110 in binary)
print(~x)  # Output: -6 (inverts all bits)
print(x << 2)  # Output: 20 (010100 in binary)
print(x >> 2)  # Output: 1 (0001 in binary)

6. Identity Operators:

Identity operators are used to compare the memory locations of two objects:

Python
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)  # Output: True (same object)
print(x is y)  # Output: False (different objects with same content)
print(x == y)  # Output: True (same content)

7. Membership Operators:

Membership operators are used to test whether a sequence is presented in an object:

Python
x = ["apple", "banana"]

print("banana" in x)  # Output: True
print("cherry" not in x)  # Output: True

Understanding and using operators effectively is fundamental in Python programming as they form the basis of many operations you perform in your code.