Python Operator Types
In Python, common operations include arithmetic operations, comparison operations, logical operations, and bitwise operations.
Arithmetic Operations
Arithmetic operations encompass basic calculations such as addition, subtraction, multiplication, and division, performed using symbols like +, -, *, /, etc. For example:
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333333333333335
print(a // b) # Output: 3, integer division operation
print(a % b) # Output: 1, modulo (remainder) operation
print(a ** b) # Output: 1000, exponentiation operation
Comparison Operations
Comparison operations are used to compare the magnitude or equality of two values using symbols such as <, >, <=, >=, ==, and !=. For example:
a = 10
b = 3
print(a < b) # Output: False
print(a > b) # Output: True
print(a <= b) # Output: False
print(a >= b) # Output: True
print(a == b) # Output: False
print(a != b) # Output: True
Logical Operations
Logical operations are used to perform calculations on boolean values, including logical AND, logical OR, and logical NOT. These use keywords such as and, or, and not. For example:
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
Bitwise Operations
Bitwise operations are used to manipulate the binary bits of integer values. They include bitwise AND, bitwise OR, bitwise XOR, and bit complementation, performed using symbols such as &, |, ^, and ~. For example:
a = 0b1010 # Decimal value 10 in binary representation
b = 0b1100 # Decimal value 12 in binary representation
print(bin(a & b)) # Output: 0b100, bitwise AND operation
print(bin(a | b)) # Output: 0b1110, bitwise OR operation
print(bin(a ^ b)) # Output: 0b110, bitwise XOR operation
print(bin(~a)) # Output: -0b1011, bit complementation operation