Python Operators

In Python, operators are symbols or keywords that perform a specific operation on one or more operands. The operands can be variables, literals, or expressions. Python supports a wide range of operators, including:

Arithmetic Operators

These operators perform mathematical operations such as addition, subtraction, multiplication, division, and modulus. For example:

1x = 5 + 3 # 8 2y = 5 - 3 # 2 3z = 5 * 3 # 15 4w = 5 / 3 # 1.666 5v = 5 % 3 # 2

Comparison Operators

These operators compare two values and return a Boolean value (True or False) based on the comparison. For example:

1x = 5 2y = 3 3print(x > y) # Output: True 4print(x < y) # Output: False 5print(x == y) # Output: False

Logical Operators

These operators perform logical operations such as and, or, and not. They return a Boolean value based on the evaluation of the logical expression. For example:

1x = 5 2y = 3 3print(x > 2 and y < 4) # Output: True 4print(x > 2 or y < 4) # Output: True 5print(not(x > 2)) # Output: False

Identity Operators

These operators compare the memory location of two variables. For example:

1x = [1, 2, 3] 2y = [1, 2, 3] 3z = x 4print(x is y) # Output: False 5print(x is z) # Output: True

Membership Operators

These operators check if an element is in a sequence (such as a list or a string). For example:

1x = [1, 2, 3] 2print(1 in x) # Output: True 3print(4 in x) # Output: False

Bitwise Operators

These operators perform bit-level operations on integers. For example:

1x = 5 # 101 2y = 3 # 011 3print(x & y) # 001 4print(x | y) # 111