Python Operators Complete Guide

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 6 of 65 ๐Ÿ“‚ Phase 2: Operators & Control Flow ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Arithmetic ยท Comparison ยท Logical (and, or, not) ยท Identity (is) ยท Membership (in) ยท Walrus (:=) ยท Precedence
Master all 8 operator families in Python: arithmetic, comparison, logical short-circuiting, identity, membership, walrus operator, and precedence.
1What is an Operator? (Operands & Expressions)

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:

๐Ÿ’ป Example 1: Basic Operator Computations
# 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
๐Ÿ” Concepts:

In a + b, + is the operator, while a and b are operands.

2Arithmetic Operators (True Division vs Floor Division)

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$.
๐Ÿ’ป Example 2: Arithmetic Operators Breakdown
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)
๐Ÿ” Why is -15 // 4 equal to -4?

Mathematical division of $-15 / 4 = -3.75$. Floor division rounds to the nearest smaller integer, which is $-4$ (not $-3$).

3Comparison Operators & Python Chained Comparisons

Comparison operators compare two values and evaluate to True or False (==, !=, >, <, >=, <=).

Python Chained Comparisons: You can chain comparisons mathematically without writing multiple and statements:

๐Ÿ’ป Example 3: Chained Comparisons in Python
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! ๐ŸŽฏ")
๐Ÿ” Efficiency Benefit:

In 80 <= score <= 90, Python evaluates the central variable score only ONCE, making it faster and cleaner.

4Logical Operators & Short-Circuit Evaluation

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:

๐Ÿ’ป Example 4: Logical Operators & Fallback Values
# 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)
๐Ÿ” How Fallbacks Work:

Since user_input is empty string ("" is Falsy), the or operator evaluates and returns the right operand: "Anonymous Guest".

5Identity Operators (is, is not) vs Equality (==)

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?).
๐Ÿ’ป Example 5: Identity (is) vs Equality (==)
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! โœ…")
๐Ÿ” Memory Pointer Explanation:

list1 and list2 have identical items [1, 2, 3], but live at two completely different memory addresses, so list1 is list2 is False.

6Membership Operators (in, not in)

Membership operators check whether a value exists inside a container (string, list, tuple, set, dictionary):

๐Ÿ’ป Example 6: Membership Operators (in, not in)
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
๐Ÿ” Performance Note:

Checking x in set or x in dict runs in instantaneous $O(1)$ constant time due to internal hash tables!

7The Walrus Operator (:=) (Assignment Expressions)

Introduced in Python 3.8 (PEP 572), the walrus operator (:=) allows you to assign a variable inside an expression, eliminating duplicate function calls:

๐Ÿ’ป Example 7: The Walrus Operator (:=)
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.")
๐Ÿ” Benefit of Walrus:

len(sample_text) is calculated only ONCE and stored directly in length for immediate reuse inside the if block.

โš ๏ธ Common Developer Pitfall: Using "is" for Number and String Comparisons

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.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Check if a student passed both math and science exams (marks >= 40 in both) using the and operator.

Python 3 Practice Challenge โ–ถ Run in Compiler
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.")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

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.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026