Operators in Python are used to perform operations on variables and values. Python provides various types of operators to handle different types of operations.
Python Operators
Operators in Python are used to perform operations on variables and values. Python provides various types of operators to handle different types of operations.
Types of Operators
- Arithmetic Operators: Used for mathematical operations
- Comparison Operators: Compare values
- Logical Operators: Used for logical expressions
- Bitwise Operators: Work at the binary level
- Assignment Operators: Assign values to variables
- Membership & Identity Operators: Check existence and identity
1. Arithmetic Operators
a = 10
b = 5
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
2. Comparison Operators
x = 10
y = 20
print(x == y) # Equal to
print(x != y) # Not equal to
print(x > y) # Greater than
print(x < y) # Less than
3. Logical Operators
a = True
b = False
print(a and b) # Logical AND
print(a or b) # Logical OR
print(not a) # Logical NOT
4. Bitwise Operators
x = 5 # 0101
y = 3 # 0011
print(x & y) # Bitwise AND
print(x | y) # Bitwise OR
print(x ^ y) # Bitwise XOR
print(~x) # Bitwise NOT
5. Assignment Operators
a = 10
a += 5 # Same as a = a + 5
a -= 3 # Same as a = a - 3
a *= 2 # Same as a = a * 2
a /= 4 # Same as a = a / 4
6. Membership & Identity Operators
list1 = [1, 2, 3, 4, 5]
print(3 in list1) # True
print(6 not in list1) # True
x = 10
y = 10
print(x is y) # True (same memory location)
print(x is not y) # False
Conclusion
Operators are a crucial part of Python programming. Understanding their usage will help you write efficient and concise code.