Operators in Python – Logical, Arithmetic, Comparison

In Python, operators are special symbols or keywords that perform operations on one or more operands. Here’s an overview of some common types of operators in Python:

1. Arithmetic Operators:

• Perform mathematical operations.
``````a = 5
b = 2

result_add = a + b  # 7

# Subtraction
result_sub = a - b  # 3

# Multiplication
result_mul = a * b  # 10

# Division
result_div = a / b  # 2.5

# Floor Division
result_floor_div = a // b  # 2

# Modulus (Remainder)
result_mod = a % b  # 1

# Exponentiation
result_exp = a ** b  # 25
``````

2. Comparison Operators:

• Compare values and return True or False.
``````x = 5
y = 10

# Equal to
is_equal = x == y  # False

# Not equal to
not_equal = x != y  # True

# Greater than
greater_than = x > y  # False

# Less than
less_than = x < y  # True

# Greater than or equal to
greater_than_equal = x >= y  # False

# Less than or equal to
less_than_equal = x <= y  # True
``````

3. Logical Operators:

• Perform logical operations.
``````p = True
q = False

# Logical AND
logical_and = p and q  # False

# Logical OR
logical_or = p or q  # True

# Logical NOT
logical_not_p = not p  # False
``````

4. Assignment Operators:

• Assign values to variables.
``````x = 5

x += 3  # Equivalent to x = x + 3

# Subtract and assign
x -= 2  # Equivalent to x = x - 2

# Multiply and assign
x *= 4  # Equivalent to x = x * 4

# Divide and assign
x /= 2  # Equivalent to x = x / 2
``````

5. Bitwise Operators:

• Perform operations on individual bits.
``````a = 5  # 101 in binary
b = 3  # 011 in binary

# Bitwise AND
bitwise_and = a & b  # 1 (001 in binary)

# Bitwise OR
bitwise_or = a | b  # 7 (111 in binary)

# Bitwise XOR
bitwise_xor = a ^ b  # 6 (110 in binary)

# Bitwise NOT
bitwise_not_a = ~a  # -6 (two's complement representation)
``````

These are just a few examples of the operators available in Python. Operators play a crucial role in performing various operations and computations in Python programs.