Python Operators and Literal Operators
Introduction
In Python, operators are symbols that perform operations on variables and values. They can handle arithmetic, comparisons, and even logical operations.
Literal operators, on the other hand, help define fixed values directly in the code.
Types of Operators
1. Arithmetic Operators
Used for basic math operations.
a = 10b = 3
print(a + b) # Addition: 13print(a - b) # Subtraction: 7print(a * b) # Multiplication: 30print(a / b) # Division: 3.3333print(a // b) # Floor Division: 3print(a % b) # Modulus: 1print(a ** b) # Exponentiation: 10002. Comparison Operators
Used to compare two values and return True or False.
x = 5y = 10
print(x > y) # Falseprint(x < y) # Trueprint(x == y) # Falseprint(x != y) # Trueprint(x >= 5) # Trueprint(y <= 5) # False3. Logical Operators
Combine multiple conditions.
x = Truey = False
print(x and y) # Falseprint(x or y) # Trueprint(not x) # False4. Assignment Operators
Used to assign and update variable values.
x = 10
x += 5 # x = x + 5 (x becomes 15)x -= 2 # x = x - 2 (x becomes 13)x *= 3 # x = x * 3 (x becomes 39)x /= 3 # x = x / 3 (x becomes 13.0)x %= 4 # x = x % 4 (x becomes 1)5. Bitwise Operators
Operate on binary representations of numbers.
a = 5 # 0101b = 3 # 0011
print(a & b) # AND: 0001 (1)print(a | b) # OR: 0111 (7)print(a ^ b) # XOR: 0110 (6)print(~a) # NOT: 1010 (-6)print(a << 1) # Left Shift: 1010 (10)print(b >> 1) # Right Shift: 0001 (1)6. Membership Operators
Check if a value exists in a sequence.
list1 = [1, 2, 3, 4]
print(2 in list1) # Trueprint(5 not in list1) # True7. Identity Operators
Compare memory locations of two objects.
x = [1, 2, 3]y = xz = [1, 2, 3]
print(x is y) # True (same object)print(x is z) # False (different objects)print(x == z) # True (same values)Literal Operators
Literal operators help create literal values directly in code.
1. String Literals
name = "John" # String literalgreeting = 'Hello, World!'2. Numeric Literals
num = 42 # Integer literalpi = 3.14 # Float literal3. Boolean Literals
is_active = Trueis_deleted = False4. List, Tuple, and Dictionary Literals
my_list = [1, 2, 3] # List literalmy_tuple = (1, 2, 3) # Tuple literalmy_dict = {"name": "Alice", "age": 25} # Dictionary literal5. None Literal
Represents the absence of a value.
x = NoneOperator Precedence
Python follows specific rules to decide the order of operations.
Order (Highest to Lowest):
**(Exponentiation)*, /, //, %(Multiplication, Division, Modulus)+, -(Addition, Subtraction)==, !=, >, <, >=, <=(Comparison)notandor
result = 5 + 2 * 3 ** 2 # 5 + 2 * 9 -> 5 + 18 -> 23Conclusion
Operators are vital in Python programming for performing calculations, comparisons, and more. By mastering operators and literal operators, you’ll be able to write more efficient and cleaner code.
Happy coding!