Operators
Operators are special symbols or keywords that perform operations on values or variables. They are categorized based on the type of operation they perform. Python provides several operators , such as:
- Arithematic Operators
- Comparison Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
- Operator Precedence
- Arithematic Operators
- + Addition
- - Substraction
- * Multiplication
- / Division
- // Floor Division
- % Modulus
- ** Exponentiation
- Comparison Operators
- == Equal
- != Not Equal
- > Greater than
- < Less than
- >= Greater than or equal
- <= Less than or equal
- Logical Operators
- and Returns True if both operands are True; otherwise, returns False.
- or Returns True if at least one operand is True; otherwise, returns False.
- not Returns the opposite boolean value of the operand (True becomes False, and vice versa).
- Assignment Operators
- = Equal
- += Add and assign
- -= Subtract and assign
- *= Multiply and assign
- /= Divide and assign
- //= Floor divide and assign
- %= Modulus and assign
- **= Exponent and assign
- Bitwise Operators
- & AND: Sets each bit to 1 if both corresponding bits of the operands are 1; otherwise, sets it to 0.
- | OR: Sets each bit to 1 if at least one of the corresponding bits of the operands is 1.
- ^ XOR: Sets each bit to 1 if exactly one of the corresponding bits is 1
- ~ NOT: Inverts all bits of the operand (changes 1 to 0 and 0 to 1)
- << Left shift: Shifts the bits of the first operand left by the number of positions specified by the second operand, filling the right with 0s.
- >> Right shift: Shifts the bits of the first operand right by the number of positions specified, filling the left with the sign bit (0 for positive, 1 for negative in two’s complement).
- Membership Operators
- in : Returns True if the specified value is found in the sequence or collection; otherwise, returns False.
- not in : Returns True if the specified value is not found in the sequence or collection; otherwise, returns False.
- Identity Operators
- is : Returns True if both operands refer to the same object in memory (i.e., they have the same memory address).
- is not : Returns True if both operands do not refer to the same object in memory.
Arithmetic operators are used to perform mathematical operations on numeric values (integers, floats, etc.). They allow you to carry out calculations like addition, subtraction, multiplication, and more. These operators are fundamental for numerical computations in Python programs.
# Arithematic Operators
x = 5
y = 3
print(x+y) # addition # 8
print(x-y) # substraction # 2
print(x*y) # multiplication # 15
print(x/y) # division # 1.666
print(x//y) # Floor division # 1
print(x%y) # Modulus # 2
print(x**y) # Exponentiation # 125
Comparison operators are used to compare two values and return a boolean result (True or False) based on the relationship between them. They are commonly used in conditional statements (e.g., if, while) to evaluate conditions and control program flow. These operators work with various data types, including numbers, strings, and other comparable objects, as long as the comparison is valid.
# Comparision Operators
x = 5
y = 3
if(x == y):
print('Equal')
else:
print('Not Equal') #Equal
if(x != y):
print('Success')
else:
print('Fail') #Success
if(x > y):
print('Success')
else:
print('Fail') #Success
if(x < y):
print('Success')
else:
print('Fail') #Fail
Logical operators are used to combine or manipulate boolean expressions (values that are either True or False). They evaluate conditions and return a boolean result, making them essential for decision-making in control structures like if, while, and loops.
# Logical Operators
x = 5
y = 3
z = 10
#and
if (x<4 and y>2):
print('Valid condition')
else:
print('Not valid condition') #Not valid condition
#or
if (x<4 or y>2):
print('Valid condition')
else:
print('Not valid condition') #Valid condition
#not
if not(x<4 or y>2):
print('Valid condition')
else:
print('Not valid condition') #Not valid condition
Assignment operators are used to assign values to variables. They combine the assignment operation (=) with other operations (like arithmetic or bitwise) to perform an operation and assign the result to a variable in a single step
# Assignment operators
x = 10
#Compound Assignment Operators
x += 5 # x = x+5; 15
x -= 2 # x = x-2; 8
x *= 3 # x = x*3; 30
x /= 2 # x = x/2; 5.0
x //= 2 # x = x//2; 5
x %= 3 # x = x % 3; 1
x **= 2 # x = x ** 2; 100
Bitwise operators are operators that perform operations on the binary representations of integers at the bit level. They manipulate individual bits (0s and 1s) of numbers directly, rather than treating the numbers as whole values. These operators are commonly used in low-level programming, such as systems programming, cryptography, and optimization tasks.
# Bitwise Operators Example
a = 10 # Binary: 1010
b = 4 # Binary: 0100
# 1. AND (&): Sets each bit to 1 if both bits are 1
print(f"AND: {a} & {b} = {a & b}") # 1010 & 0100 = 0000 (0)
# 2. OR (|): Sets each bit to 1 if one or both bits are 1
print(f"OR: {a} | {b} = {a | b}") # 1010 | 0100 = 1110 (14)
# 3. XOR (^): Sets each bit to 1 if only one bit is 1
print(f"XOR: {a} ^ {b} = {a ^ b}") # 1010 ^ 0100 = 1110 (14)
# 4. NOT (~): Inverts all bits (returns -x-1 due to 2's complement)
print(f"NOT: ~{a} = {~a}") # ~1010 = -1011 (-11)
# 5. Left Shift (<<): Shifts bits left, fills with 0s
print(f"Left Shift: {a} << 2 = {a << 2}") # 1010 << 2 = 101000 (40)
# 6. Right Shift (>>): Shifts bits right, fills with sign bit
print(f"Right Shift: {a} >> 2 = {a >> 2}") # 1010 >> 2 = 0010 (2)
Membership operators are used to test whether a value or element is present in a sequence or collection, such as strings, lists, tuples, sets, or dictionaries. They return a boolean result (True or False) based on whether the value is found. These operators are commonly used in conditional statements and loops to check for membership in data structures.
# Membership Operators Example (without f-strings)
numbers = [1, 3, 5, 7]
text = "hello"
my_dict = {"name": "Alice", "age": 25}
my_set = {10, 20, 30}
# Using 'in' with .format() for printing
print("5 in {}: {}".format(numbers, 5 in numbers)) # True
print("'h' in '{}': {}".format(text, 'h' in text)) # True
print("'name' in {}: {}".format(my_dict, 'name' in my_dict)) # True (checks keys)
print("10 in {}: {}".format(my_set, 10 in my_set)) # True
# Using 'not in' with % operator for printing
print("2 not in %s: %s" % (numbers, 2 not in numbers)) # True
print("'z' not in '%s': %s" % (text, 'z' not in text)) # True
print("'value' not in %s: %s" % (my_dict, 'value' not in my_dict)) # True (not a key)
print("15 not in %s: %s" % (my_set, 15 not in my_set)) # True
# Practical example with string concatenation
user_input = "apple"
valid_fruits = ["apple", "banana", "orange"]
print("Is '" + user_input + "' a valid fruit? " + str(user_input in valid_fruits)) # True
Identity operators are used to compare the memory identity of two objects, checking whether they refer to the same object in memory, not just whether their values are equal. They return a boolean result (True or False).
# Identity Operators Example (without f-strings)
x = [1, 2, 3]
y = x # Same object
z = [1, 2, 3] # Different object with same value
a = 42
b = 42 # Likely same object due to integer interning
c = None
# Using 'is' with .format() for printing
print("x is y: {}".format(x is y)) # True (same object)
print("x is z: {}".format(x is z)) # False (different objects)
print("a is b: {}".format(a is b)) # True (due to integer interning)
print("c is None: {}".format(c is None)) # True
# Using 'is not' with % operator for printing
print("x is not z: %s" % (x is not z)) # True (different objects)
print("a is not None: %s" % (a is not None)) # True
print("x is not y: %s" % (x is not y)) # False (same object)
# Verify with id() using string concatenation
print("id(x): " + str(id(x)) + ", id(y): " + str(id(y))) # Same ID
print("id(x): " + str(id(x)) + ", id(z): " + str(id(z))) # Different IDs
Operator Precedence
Operations are performed in this order (highest to lowest):Parentheses: ()
Exponentiation: **
Bitwise NOT, Unary +/-: ~ + -
Multiplication, Division, etc.: * / // %
Addition/Subtraction: + -
Bitwise shifts: << >>
Bitwise AND: &
Bitwise XOR: ^
Bitwise OR: |
Comparisons: == != > < >= <=
Identity operators: is is not
Membership operators: in not in
Logical NOT: not
Logical AND: and
Logical OR: or