Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
Operators in Python are symbols that enable you to perform specific operations on operands, such as variables and values. Python has several types of operators, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. In this tutorial, we'll briefly discuss each type of operator and provide examples of their usage.
Example:
a = 10 b = 3 print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.3333333333333335 print(a // b) # 3 print(a % b) # 1 print(a ** b) # 1000
Example:
x = 5 y = 10 print(x == y) # False print(x != y) # True print(x > y) # False print(x < y) # True print(x >= y) # False print(x <= y) # True
Arithmetic operators in Python:
a = 5 b = 2 addition = a + b subtraction = a - b multiplication = a * b division = a / b modulus = a % b print(f"Addition: {addition}, Subtraction: {subtraction}, Multiplication: {multiplication}, Division: {division}, Modulus: {modulus}")
Comparison operators in Python:
x = 5 y = 8 greater_than = x > y equal_to = x == y not_equal = x != y print(f"Greater Than: {greater_than}, Equal To: {equal_to}, Not Equal: {not_equal}")
Logical operators in Python:
is_true = True is_false = False logical_and = is_true and is_false logical_or = is_true or is_false logical_not = not is_true print(f"Logical AND: {logical_and}, Logical OR: {logical_or}, Logical NOT: {logical_not}")
Bitwise operators in Python:
x = 5 y = 3 bitwise_and = x & y bitwise_or = x | y bitwise_xor = x ^ y print(f"Bitwise AND: {bitwise_and}, Bitwise OR: {bitwise_or}, Bitwise XOR: {bitwise_xor}")
Assignment operators in Python:
a = 5 a += 2 # Equivalent to a = a + 2 print(a)
Membership operators in Python:
numbers = [1, 2, 3, 4, 5] is_in = 3 in numbers is_not_in = 6 not in numbers print(f"Is In: {is_in}, Not In: {is_not_in}")
Identity operators in Python:
x = [1, 2, 3] y = [1, 2, 3] is_same_object = x is y is_not_same_object = x is not y print(f"Is Same Object: {is_same_object}, Not Same Object: {is_not_same_object}")
Operator precedence in Python:
result = 5 + 3 * 2 # Multiplication has higher precedence print(result)
Custom operators and operator overloading in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) p1 = Point(1, 2) p2 = Point(3, 4) p3 = p1 + p2 print(f"Result: ({p3.x}, {p3.y})")