Python Operators Complete Guide
An operator is a special symbol or keyword that performs a computation on one or more operands (values/variables). Python organizes operators into 8 distinct families:
# Basic operator examples:
a = 10
b = 5
print("1. Arithmetic (a + b):", a + b) # 15
print("2. Comparison (a > b):", a > b) # True
print("3. Logical (a > 0 and b > 0):", a > 0 and b > 0) # True
In a + b, + is the operator, while a and b are operands.
Python provides 7 core arithmetic operators. Notice the important difference between / and //:
/: True Float Division โ ALWAYS returns a float (e.g.10 / 2 -> 5.0).//: Floor Division โ Truncates decimals and rounds downward toward negative infinity (e.g.15 // 4 -> 3, but-15 // 4 -> -4).%: Modulus โ Returns remainder after division.**: Exponentiation (Power) โ Calculates $a^b$.
print("15 / 4 (True float division):", 15 / 4) # 3.75 (Float)
print("15 // 4 (Floor integer division):", 15 // 4) # 3 (Int)
print("-15 // 4 (Negative floor division):", -15 // 4) # -4 (Rounds down to -infinity!)
print("15 % 4 (Modulus remainder):", 15 % 4) # 3 (Remainder)
print("2 ** 5 (Exponentiation power):", 2 ** 5) # 32 (2 to the power 5)
Mathematical division of $-15 / 4 = -3.75$. Floor division rounds to the nearest smaller integer, which is $-4$ (not $-3$).
Comparison operators compare two values and evaluate to True or False (==, !=, >, <, >=, <=).
Python Chained Comparisons: You can chain comparisons mathematically without writing multiple and statements:
score = 85
# In C/Java you write: score >= 80 && score <= 90
# In Python you write clean chained math:
if 80 <= score <= 90:
print(f"Grade B: Score {score} is between 80 and 90! ๐ฏ")
In 80 <= score <= 90, Python evaluates the central variable score only ONCE, making it faster and cleaner.
Python uses English keywords: and, or, and not.
Short-Circuiting: Python stops evaluating as soon as the outcome is determined. Moreover, Python logical operators return the actual operand value, enabling the widely-used fallback pattern:
# 1. Logical and / or
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry Allowed! ๐๏ธ")
# 2. Returning actual operands (Fallback pattern)
user_input = ""
default_name = user_input or "Anonymous Guest"
print("Welcome,", default_name)
Since user_input is empty string ("" is Falsy), the or operator evaluates and returns the right operand: "Anonymous Guest".
Never confuse == and is:
==: Checks Value Equality (are the contents identical?).is: Checks Memory Address Identity (do both variables point to the same physical object in RAM?).
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print("list1 == list2 (Values match?):", list1 == list2) # True
print("list1 is list2 (Same memory?):", list1 is list2) # False
# Rule: Use 'is' strictly for singleton constants like None, True, False
target_val = None
if target_val is None:
print("Value is None! โ
")
list1 and list2 have identical items [1, 2, 3], but live at two completely different memory addresses, so list1 is list2 is False.
Membership operators check whether a value exists inside a container (string, list, tuple, set, dictionary):
fruits = ["apple", "banana", "mango"]
print("Is apple in list?", "apple" in fruits) # True
print("Is grape in list?", "grape" in fruits) # False
# Substring check in text:
sentence = "python programming is awesome"
print("Is 'program' in sentence?", "program" in sentence) # True
Checking x in set or x in dict runs in instantaneous $O(1)$ constant time due to internal hash tables!
Introduced in Python 3.8 (PEP 572), the walrus operator (:=) allows you to assign a variable inside an expression, eliminating duplicate function calls:
sample_text = "Python Masterclass 2026"
# Assign length and test condition in ONE line:
if (length := len(sample_text)) > 10:
print(f"Text is long! It contains {length} characters.")
len(sample_text) is calculated only ONCE and stored directly in length for immediate reuse inside the if block.
Do not write "if x is 100:" or "if name is 'admin':". Use "==" for all value checks. Use "is" strictly for singleton objects like None, True, False.
Check if a student passed both math and science exams (marks >= 40 in both) using the and operator.
math_score = 75
science_score = 82
if math_score >= 40 and science_score >= 40:
print("๐ Congratulations, you passed both exams!")
else:
print("โ You need to retake one or more exams.")
Q Why does Python logical "or" return the first truthy value instead of True?
Returning the actual operand enables powerful idioms like default fallback values: name = input_name or "Anonymous".
Q What is the difference between / and // in Python?
/ performs true float division (10 / 2 = 5.0). // performs floor division, discarding the remainder and rounding toward negative infinity (10 // 3 = 3, -10 // 3 = -4).
Q What is the time complexity of checking "item in collection"?
For lists and tuples, "in" runs in linear O(N) time. For sets and dictionaries, "in" runs in instantaneous constant O(1) time due to hash tables.