Python operators are special symbols that carry out arithmetic, logical, and comparison operations. These operators work with operands (values or variables) to produce results. Python provides several categories of operators, each serving specific purposes in programming logic and mathematical computations.
Arithmetic operators perform mathematical calculations on numeric values. Python supports seven arithmetic operators that handle basic mathematical operations.
The addition operator adds two or more values together. This Python operator works with numbers, strings, and lists.
# Addition with numbers
result = 15 + 25
print(result) # Output: 40
# Addition with strings (concatenation)
greeting = "Hello" + " World"
print(greeting) # Output: Hello World
The subtraction operator subtracts the right operand from the left operand.
# Subtraction operation
difference = 100 - 35
print(difference) # Output: 65
# Negative numbers
negative_value = -42
print(negative_value) # Output: -42
The multiplication operator multiplies two values or repeats strings and lists.
# Multiplication with numbers
product = 12 * 8
print(product) # Output: 96
# String repetition
repeated_text = "Python" * 3
print(repeated_text) # Output: PythonPythonPython
The division operator performs floating-point division, always returning a float result.
# Division operation
quotient = 20 / 4
print(quotient) # Output: 5.0
# Division with remainder
decimal_result = 17 / 5
print(decimal_result) # Output: 3.4
Floor division returns the largest integer less than or equal to the division result.
# Floor division
floor_result = 17 // 5
print(floor_result) # Output: 3
# Floor division with negative numbers
negative_floor = -17 // 5
print(negative_floor) # Output: -4
The modulus operator returns the remainder after division.
# Modulus operation
remainder = 17 % 5
print(remainder) # Output: 2
# Check even or odd
number = 24
is_even = number % 2 == 0
print(is_even) # Output: True
The exponentiation operator raises a number to a specified power.
# Exponentiation
power_result = 2 ** 5
print(power_result) # Output: 32
# Square root using fractional exponent
square_root = 16 ** 0.5
print(square_root) # Output: 4.0
Comparison operators compare two values and return Boolean results (True or False). These Python operators are essential for conditional statements and decision-making in programs.
Checks if two values are equal.
# Equality comparison
is_equal = 10 == 10
print(is_equal) # Output: True
# String comparison
text_match = "python" == "python"
print(text_match) # Output: True
Checks if two values are not equal.
# Inequality comparison
not_equal = 15 != 20
print(not_equal) # Output: True
# Different data types
different_types = 5 != "5"
print(different_types) # Output: True
Checks if the left operand is greater than the right operand.
# Greater than comparison
is_greater = 25 > 15
print(is_greater) # Output: True
# String comparison (alphabetical order)
string_greater = "zebra" > "apple"
print(string_greater) # Output: True
Checks if the left operand is less than the right operand.
# Less than comparison
is_less = 10 < 20
print(is_less) # Output: True
# Age comparison
age = 16
is_minor = age < 18
print(is_minor) # Output: True
Checks if the left operand is greater than or equal to the right operand.
# Greater than or equal comparison
is_greater_equal = 30 >= 30
print(is_greater_equal) # Output: True
# Grade evaluation
score = 85
passed = score >= 60
print(passed) # Output: True
Checks if the left operand is less than or equal to the right operand.
# Less than or equal comparison
is_less_equal = 25 <= 30
print(is_less_equal) # Output: True
# Temperature check
temperature = 32
is_freezing = temperature <= 32
print(is_freezing) # Output: True
Logical operators perform logical operations on Boolean values. These Python operators are crucial for combining multiple conditions in conditional statements.
Returns True only if both operands are True.
# AND operation
both_true = True and True
print(both_true) # Output: True
# Practical example
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive) # Output: True
Returns True if at least one operand is True.
# OR operation
either_true = True or False
print(either_true) # Output: True
# Weekend check
day = "Saturday"
is_weekend = day == "Saturday" or day == "Sunday"
print(is_weekend) # Output: True
Returns the opposite Boolean value of the operand.
# NOT operation
opposite = not True
print(opposite) # Output: False
# Negation in conditions
is_raining = False
go_outside = not is_raining
print(go_outside) # Output: True
Assignment operators assign values to variables. Python provides various assignment operators that combine assignment with arithmetic operations.
Assigns a value to a variable.
# Simple assignment
number = 42
name = "Alice"
is_active = True
Adds the right operand to the left operand and assigns the result.
# Addition assignment
count = 10
count += 5 # Equivalent to count = count + 5
print(count) # Output: 15
# String concatenation
message = "Hello"
message += " World"
print(message) # Output: Hello World
Subtracts the right operand from the left operand and assigns the result.
# Subtraction assignment
balance = 1000
balance -= 150 # Equivalent to balance = balance - 150
print(balance) # Output: 850
Multiplies the left operand by the right operand and assigns the result.
# Multiplication assignment
value = 8
value *= 3 # Equivalent to value = value * 3
print(value) # Output: 24
Divides the left operand by the right operand and assigns the result.
# Division assignment
total = 100
total /= 4 # Equivalent to total = total / 4
print(total) # Output: 25.0
Calculates the modulus and assigns the result.
# Modulus assignment
number = 17
number %= 5 # Equivalent to number = number % 5
print(number) # Output: 2
Raises the left operand to the power of the right operand and assigns the result.
# Exponentiation assignment
base = 3
base **= 4 # Equivalent to base = base ** 4
print(base) # Output: 81
Performs floor division and assigns the result.
# Floor division assignment
dividend = 22
dividend //= 7 # Equivalent to dividend = dividend // 7
print(dividend) # Output: 3
Bitwise operators perform operations on individual bits of integers. These Python operators are useful for low-level programming and optimization tasks.
Performs bitwise AND operation on each pair of corresponding bits.
# Bitwise AND
result = 12 & 10 # 1100 & 1010 = 1000
print(result) # Output: 8
print(bin(result)) # Output: 0b1000
Performs bitwise OR operation on each pair of corresponding bits.
# Bitwise OR
result = 12 | 10 # 1100 | 1010 = 1110
print(result) # Output: 14
print(bin(result)) # Output: 0b1110
Performs bitwise XOR operation on each pair of corresponding bits.
# Bitwise XOR
result = 12 ^ 10 # 1100 ^ 1010 = 0110
print(result) # Output: 6
print(bin(result)) # Output: 0b110
Performs bitwise NOT operation (one’s complement).
# Bitwise NOT
result = ~12 # ~1100 = -13 (in two's complement)
print(result) # Output: -13
Shifts bits to the left by specified positions.
# Left shift
result = 5 << 2 # 101 << 2 = 10100
print(result) # Output: 20
print(bin(result)) # Output: 0b10100
Shifts bits to the right by specified positions.
# Right shift
result = 20 >> 2 # 10100 >> 2 = 101
print(result) # Output: 5
print(bin(result)) # Output: 0b101
Membership operators test whether a value is present in a sequence (string, list, tuple, etc.).
Returns True if a value is found in the sequence.
# IN operator with lists
numbers = [1, 2, 3, 4, 5]
exists = 3 in numbers
print(exists) # Output: True
# IN operator with strings
text = "Python Programming"
contains = "Python" in text
print(contains) # Output: True
Returns True if a value is not found in the sequence.
# NOT IN operator
fruits = ["apple", "banana", "orange"]
not_present = "grape" not in fruits
print(not_present) # Output: True
# Character not in string
letter_missing = "z" not in "hello"
print(letter_missing) # Output: True
Identity operators compare the memory addresses of two objects to determine if they are the same object.
Returns True if both operands refer to the same object.
# IS operator
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
same_object = list1 is list3
print(same_object) # Output: True
different_objects = list1 is list2
print(different_objects) # Output: False
Returns True if operands refer to different objects.
# IS NOT operator
x = 10
y = 20
different = x is not y
print(different) # Output: True
# None comparison
value = None
not_none = value is not None
print(not_none) # Output: False
Python operators follow a specific precedence order that determines which operations are performed first in complex expressions. Understanding operator precedence is crucial for writing correct Python code.
The precedence order (highest to lowest):
# Operator precedence example
result = 2 + 3 * 4 ** 2
print(result) # Output: 50 (not 400)
# Calculation: 2 + 3 * 16 = 2 + 48 = 50
# Using parentheses to change precedence
result_with_parentheses = (2 + 3) * 4 ** 2
print(result_with_parentheses) # Output: 80
# Calculation: 5 * 16 = 80
Here’s a comprehensive example demonstrating various Python operators in a practical scenario:
# Import necessary modules
import math
# Complete Python operators demonstration
class CalculatorDemo:
def __init__(self):
self.result = 0
self.operations_count = 0
def arithmetic_operations(self):
"""Demonstrate arithmetic operators"""
print("=== Arithmetic Operators Demo ===")
# Basic arithmetic
num1, num2 = 25, 8
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
floor_division = num1 // num2
modulus = num1 % num2
exponentiation = num1 ** 2
print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} * {num2} = {multiplication}")
print(f"Division: {num1} / {num2} = {division}")
print(f"Floor Division: {num1} // {num2} = {floor_division}")
print(f"Modulus: {num1} % {num2} = {modulus}")
print(f"Exponentiation: {num1} ** 2 = {exponentiation}")
# String operations
text1, text2 = "Python", "Operators"
concatenation = text1 + " " + text2
repetition = text1 * 3
print(f"String concatenation: '{text1}' + ' ' + '{text2}' = '{concatenation}'")
print(f"String repetition: '{text1}' * 3 = '{repetition}'")
def comparison_operations(self):
"""Demonstrate comparison operators"""
print("\n=== Comparison Operators Demo ===")
x, y = 15, 20
equal = x == y
not_equal = x != y
greater_than = x > y
less_than = x < y
greater_equal = x >= 15
less_equal = y <= 20
print(f"Equal: {x} == {y} = {equal}")
print(f"Not Equal: {x} != {y} = {not_equal}")
print(f"Greater Than: {x} > {y} = {greater_than}")
print(f"Less Than: {x} < {y} = {less_than}")
print(f"Greater or Equal: {x} >= 15 = {greater_equal}")
print(f"Less or Equal: {y} <= 20 = {less_equal}")
def logical_operations(self):
"""Demonstrate logical operators"""
print("\n=== Logical Operators Demo ===")
is_sunny = True
is_weekend = False
temperature = 25
# Complex logical conditions
perfect_day = is_sunny and (is_weekend or temperature > 20)
stay_inside = not is_sunny or temperature < 10
go_picnic = is_sunny and is_weekend and temperature > 15
print(f"Is sunny: {is_sunny}")
print(f"Is weekend: {is_weekend}")
print(f"Temperature: {temperature}°C")
print(f"Perfect day: {perfect_day}")
print(f"Stay inside: {stay_inside}")
print(f"Go picnic: {go_picnic}")
def assignment_operations(self):
"""Demonstrate assignment operators"""
print("\n=== Assignment Operators Demo ===")
# Various assignment operations
score = 100
print(f"Initial score: {score}")
score += 25 # Addition assignment
print(f"After += 25: {score}")
score -= 15 # Subtraction assignment
print(f"After -= 15: {score}")
score *= 2 # Multiplication assignment
print(f"After *= 2: {score}")
score /= 4 # Division assignment
print(f"After /= 4: {score}")
score //= 2 # Floor division assignment
print(f"After //= 2: {score}")
score %= 10 # Modulus assignment
print(f"After %= 10: {score}")
score **= 3 # Exponentiation assignment
print(f"After **= 3: {score}")
def bitwise_operations(self):
"""Demonstrate bitwise operators"""
print("\n=== Bitwise Operators Demo ===")
a, b = 12, 10 # Binary: 1100 and 1010
and_result = a & b
or_result = a | b
xor_result = a ^ b
not_result = ~a
left_shift = a << 2
right_shift = a >> 2
print(f"a = {a} (binary: {bin(a)})")
print(f"b = {b} (binary: {bin(b)})")
print(f"a & b = {and_result} (binary: {bin(and_result)})")
print(f"a | b = {or_result} (binary: {bin(or_result)})")
print(f"a ^ b = {xor_result} (binary: {bin(xor_result)})")
print(f"~a = {not_result}")
print(f"a << 2 = {left_shift} (binary: {bin(left_shift)})")
print(f"a >> 2 = {right_shift} (binary: {bin(right_shift)})")
def membership_operations(self):
"""Demonstrate membership operators"""
print("\n=== Membership Operators Demo ===")
programming_languages = ["Python", "Java", "C++", "JavaScript", "Go"]
favorite_language = "Python"
unknown_language = "COBOL"
is_favorite = favorite_language in programming_languages
is_unknown = unknown_language not in programming_languages
print(f"Programming languages: {programming_languages}")
print(f"'{favorite_language}' in list: {is_favorite}")
print(f"'{unknown_language}' not in list: {is_unknown}")
# String membership
sentence = "Python operators are powerful"
has_python = "Python" in sentence
no_java = "Java" not in sentence
print(f"Sentence: '{sentence}'")
print(f"Contains 'Python': {has_python}")
print(f"Does not contain 'Java': {no_java}")
def identity_operations(self):
"""Demonstrate identity operators"""
print("\n=== Identity Operators Demo ===")
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
same_reference = list1 is list3
different_reference = list1 is not list2
equal_content = list1 == list2
print(f"list1: {list1} (id: {id(list1)})")
print(f"list2: {list2} (id: {id(list2)})")
print(f"list3: {list3} (id: {id(list3)})")
print(f"list1 is list3: {same_reference}")
print(f"list1 is not list2: {different_reference}")
print(f"list1 == list2: {equal_content}")
def operator_precedence_demo(self):
"""Demonstrate operator precedence"""
print("\n=== Operator Precedence Demo ===")
# Complex expression with multiple operators
result1 = 2 + 3 * 4 ** 2 > 45 and True or False
result2 = (2 + 3) * 4 ** 2 > 45 and True or False
print(f"2 + 3 * 4 ** 2 > 45 and True or False = {result1}")
print(f"(2 + 3) * 4 ** 2 > 45 and True or False = {result2}")
# Practical example: calculating compound interest
principal = 1000
rate = 0.05
time = 3
compound_interest = principal * (1 + rate) ** time
print(f"Compound Interest: ${principal} * (1 + {rate}) ** {time} = ${compound_interest:.2f}")
def run_all_demos(self):
"""Run all operator demonstrations"""
print("Python Operators Complete Demonstration")
print("=" * 50)
self.arithmetic_operations()
self.comparison_operations()
self.logical_operations()
self.assignment_operations()
self.bitwise_operations()
self.membership_operations()
self.identity_operations()
self.operator_precedence_demo()
print("\n" + "=" * 50)
print("Python Operators Demo Complete!")
# Run the complete demonstration
if __name__ == "__main__":
demo = CalculatorDemo()
demo.run_all_demos()
Expected Output:
Python Operators Complete Demonstration
==================================================
=== Arithmetic Operators Demo ===
Addition: 25 + 8 = 33
Subtraction: 25 - 8 = 17
Multiplication: 25 * 8 = 200
Division: 25 / 8 = 3.125
Floor Division: 25 // 8 = 3
Modulus: 25 % 8 = 1
Exponentiation: 25 ** 2 = 625
String concatenation: 'Python' + ' ' + 'Operators' = 'Python Operators'
String repetition: 'Python' * 3 = 'PythonPythonPython'
=== Comparison Operators Demo ===
Equal: 15 == 20 = False
Not Equal: 15 != 20 = True
Greater Than: 15 > 20 = False
Less Than: 15 < 20 = True
Greater or Equal: 15 >= 15 = True
Less or Equal: 20 <= 20 = True
=== Logical Operators Demo ===
Is sunny: True
Is weekend: False
Temperature: 25°C
Perfect day: True
Stay inside: False
Go picnic: False
=== Assignment Operators Demo ===
Initial score: 100
After += 25: 125
After -= 15: 110
After *= 2: 220
After /= 4: 55.0
After //= 2: 27.0
After %= 10: 7.0
After **= 3: 343.0
=== Bitwise Operators Demo ===
a = 12 (binary: 0b1100)
b = 10 (binary: 0b1010)
a & b = 8 (binary: 0b1000)
a | b = 14 (binary: 0b1110)
a ^ b = 6 (binary: 0b110)
~a = -13
a << 2 = 48 (binary: 0b110000)
a >> 2 = 3 (binary: 0b11)
=== Membership Operators Demo ===
Programming languages: ['Python', 'Java', 'C++', 'JavaScript', 'Go']
'Python' in list: True
'COBOL' not in list: True
Sentence: 'Python operators are powerful'
Contains 'Python': True
Does not contain 'Java': True
=== Identity Operators Demo ===
list1: [1, 2, 3] (id: 140234567890432)
list2: [1, 2, 3] (id: 140234567890528)
list3: [1, 2, 3] (id: 140234567890432)
list1 is list3: True
list1 is not list2: True
list1 == list2: True
=== Operator Precedence Demo ===
2 + 3 * 4 ** 2 > 45 and True or False = True
(2 + 3) * 4 ** 2 > 45 and True or False = True
Compound Interest: $1000 * (1 + 0.05) ** 3 = $1157.63
==================================================
Python Operators Demo Complete!
This comprehensive guide covers all Python operators with detailed explanations and practical examples. Understanding these operators is essential for writing efficient Python code and solving complex programming problems. Practice using these operators in different scenarios to master Python programming fundamentals.