Python tutorials  /  Python Operators
Chapter 4 · Python

Python Operators

An operator in Python is a special symbol or keyword that performs a specific operation on one or more operands (values or variables) and returns a result. Python categorizes operators into arithmetic, comparison, logical, assignment, membership ('in', 'not in'), and identity ('is', 'is not') operators, the last two being somewhat unique compared to languages like Java.

Operators are the action words of Python, just like in any language — they tell Python what to actually do with your data. Beyond the familiar math symbols (+, -, *, /) and comparisons (==, >, <) that most languages share, Python adds a couple of especially handy operators: 'in' lets you ask 'is this item part of that collection?' almost like plain English (e.g., 'apple' in fruit_basket), and 'is' lets you check whether two variables are literally the exact same object in memory, not just equal in value.

Consider an e-commerce discount-checking script. The 'in' membership operator can instantly check whether a customer's coupon code exists within a list of valid active codes (e.g., 'if coupon_code in valid_codes:'), which is far more readable than manually looping through the list checking each item. Meanwhile, logical operators ('and', 'or', 'not' — Python uses actual words instead of Java's &&, ||, !) combine multiple conditions, such as checking 'if cart_total > 500 and is_premium_member:' to decide whether to apply free shipping, a pattern used constantly in real Python-based backend and automation scripts.

Operators are the fundamental tools that allow programs to perform calculations, compare values, combine conditions, and check relationships between data — without them, a program could only store static values with no way to transform, compare, or make decisions based on that data. Python's operators are designed to be especially readable (using words like 'and', 'or', 'not', 'in' instead of purely symbolic equivalents), aligning with the language's overall philosophy of code that reads almost like natural English, while still providing the full power needed for real-world calculations and logic.

  • Arithmetic Operators: Perform mathematical operations: addition (+), subtraction (-), multiplication (*), true division (/, always returns a float), floor division (//, truncates to an integer-style result), modulus (%), and exponentiation (**).
  • Comparison Operators: Compare two values and return a boolean result: equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
  • Logical Operators: Combine boolean expressions using actual English words rather than symbols: 'and' (both must be true), 'or' (at least one must be true), and 'not' (inverts a boolean value), also using short-circuit evaluation like Java's && and ||.
  • Membership Operators: 'in' and 'not in' check whether a value exists (or doesn't exist) within a sequence like a list, tuple, string, or dictionary's keys, returning a boolean result.
  • Identity Operators: 'is' and 'is not' check whether two variables refer to the exact same object in memory (identity), which is a fundamentally different check from '==', which only compares whether two values are equal.
result = operand1 operator operand2 # Membership: value in collection # Identity: variable1 is variable2
A beginner wants to build a simple program that checks if a student's score qualifies for a scholarship (score >= 85 AND attendance >= 90), checks if a given username already exists in a list of registered users using the membership operator, and understands the difference between '==' and 'is' when comparing values.
Arithmetic and Comparison Operators for Scholarship Eligibility
This example uses arithmetic and comparison operators to check if a student's average score and attendance meet scholarship eligibility criteria, combined with a logical operator.
Python
math_score = 88 science_score = 92 average = (math_score + science_score) / 2 attendance = 95 is_eligible = (average >= 85) and (attendance >= 90) print("Average Score:", average) print("Scholarship Eligible:", is_eligible)
Average Score: 90.0 Scholarship Eligible: True
The '+' operator adds the two scores, and '/' performs true division, always returning a float (90.0) even though both operands are whole numbers, unlike Java's integer division truncation. The 'and' keyword (not '&&' like in Java) combines both comparison results — the overall expression is only 'True' if BOTH the average and attendance conditions are individually true, demonstrating Python's readable, word-based logical operators.
Membership ('in') vs Identity ('is') Operators
This example demonstrates the crucial difference between the 'in' membership operator (checking if a value exists within a collection) and the 'is' identity operator (checking if two variables reference the exact same object), contrasted with the standard '==' equality operator.
Python
registered_users = ["alice", "bob", "charlie"] new_username = "bob" print("Username taken:", new_username in registered_users) list_a = [1, 2, 3] list_b = [1, 2, 3] list_c = list_a print("list_a == list_b:", list_a == list_b) print("list_a is list_b:", list_a is list_b) print("list_a is list_c:", list_a is list_c)
Username taken: True list_a == list_b: True list_a is list_b: False list_a is list_c: True
'new_username in registered_users' checks whether the value "bob" exists anywhere within the list, returning True since it's present. 'list_a == list_b' returns True because both lists contain equal VALUES ([1, 2, 3]), even though they are two separate, independently created list objects in memory — this is why 'list_a is list_b' returns False, since 'is' checks OBJECT IDENTITY (same memory location), not value equality. However, 'list_c = list_a' makes 'list_c' point to the exact same object as 'list_a' (not a copy), so 'list_a is list_c' correctly returns True.
  • Using 'is' Instead of '==' to Compare Values: Beginners often use 'is' when they actually mean to check value equality, writing something like 'if user_input is "yes":' instead of 'if user_input == "yes":'. While this might sometimes appear to work due to Python's internal caching of small integers and short strings, it is NOT reliable for general value comparison and can produce unexpected 'False' results for larger strings, numbers, or any mutable objects like lists — '==' should always be used for comparing values, and 'is' reserved specifically for checking against 'None' or verifying true object identity.
  • Forgetting Python Uses 'and'/'or'/'not' Instead of &&/||/!: Developers coming from Java, C, or JavaScript often instinctively write 'if (a > 5 && b < 10):' in Python, which raises a 'SyntaxError: invalid syntax', since Python does not recognize '&&', '||', or '!' as valid logical operators at all — it exclusively uses the English words 'and', 'or', and 'not' instead.
  • Confusing True Division (/) with Floor Division (//): Expecting '/' to truncate like integer division in Java (e.g., assuming '9 / 2' returns '4') is a common mistake, since Python 3's '/' always performs true division and returns a float ('4.5'). The floor division operator '//' must be explicitly used to get a truncated, integer-style result ('9 // 2' returns '4').
  • Chaining Comparisons Incorrectly Without Realizing Python Supports It Natively: Writing an overly verbose 'if age >= 18 and age <= 65:' when Python actually supports elegant CHAINED comparisons natively, allowing the equivalent, more readable 'if 18 <= age <= 65:' directly — beginners unfamiliar with this Python-specific feature sometimes miss this cleaner syntax option, or worse, mistakenly assume 'if 18 <= age <= 65' behaves like separate boolean values being compared rather than a genuine combined range check.
  • Use '==' for Value Comparison, Reserve 'is' for None and Identity Checks: Always use '==' when comparing whether two values are equal, and reserve the 'is' operator specifically for checking against the singleton 'None' value (e.g., 'if result is None:') or for genuine cases where verifying that two variables reference the exact same object in memory is intentionally required.
  • Leverage Python's Readable Chained Comparisons: Take advantage of Python's native support for chained comparisons (e.g., 'if 0 <= score <= 100:') instead of writing more verbose equivalent expressions with 'and', since this feature is unique to Python and produces cleaner, more mathematically intuitive range-checking code.
  • Use 'in' for Readable Membership Checks Instead of Manual Loops: Whenever checking if a value exists within a list, tuple, string, or dictionary's keys, use the 'in' operator directly (e.g., 'if item in my_list:') rather than manually writing a loop with a flag variable to check for the item's presence, since 'in' is both more concise and more idiomatic Python.
  • Use Parentheses to Clarify Complex Logical Expressions: Even though Python's operator precedence rules are well-defined, use parentheses to make complex conditions combining 'and', 'or', and comparison operators explicit and immediately readable, especially when mixing 'and' and 'or' together in the same expression, since 'and' has higher precedence than 'or' and this can otherwise cause subtle logic errors if not made clear.
What is the difference between '==' and 'is' in Python?
'==' checks for VALUE EQUALITY, meaning it compares whether two operands hold logically equal values, regardless of whether they are the same object in memory (this is the operator you should almost always use for general comparisons). 'is' checks for OBJECT IDENTITY, meaning it verifies whether two variables actually point to the exact same object in memory (the same memory address) — two separate lists with identical contents, like '[1, 2, 3]' and another separately-created '[1, 2, 3]', will return True for '==' (equal values) but False for 'is' (different objects in memory), unless one variable was directly assigned from the other, making them reference the same object. 'is' is specifically recommended for checking against 'None' (e.g., 'if x is None:'), since 'None' is a unique singleton object in Python, and this check is both more idiomatic and slightly more efficient than '==' in this specific case.
Why does Python use 'and', 'or', and 'not' instead of &&, ||, and ! like many other languages?
This design choice reflects Python's overall philosophy, guided by its creator Guido van Rossum, of prioritizing code readability and resembling natural English wherever reasonably possible, rather than relying purely on terse symbolic operators inherited from C-style languages. Using actual English words for logical operators makes conditional expressions read almost like plain sentences (e.g., 'if is_admin and not is_banned:'), which the language's designers felt improved comprehension for both beginners and experienced developers alike, at essentially zero performance cost, since these are still just as efficiently short-circuit-evaluated internally as their symbolic '&&'/'||' counterparts in other languages.
Explain Python's chained comparison feature with an example, and describe how it differs from writing the equivalent expression with explicit 'and'.
Python natively supports chaining multiple comparison operators together in a single expression, such as '0 <= score <= 100', which Python evaluates as checking BOTH '0 <= score' AND 'score <= 100' simultaneously, correctly determining if 'score' falls within that entire range — this is functionally equivalent to writing '(0 <= score) and (score <= 100)' explicitly with 'and', but the chained version is more concise and mathematically intuitive to read, closely mirroring how range conditions are naturally written in mathematics. Under the hood, Python evaluates 'score' only once in the chained version (rather than potentially evaluating a more complex middle expression twice, if it were something more elaborate than a simple variable), and like the equivalent 'and' expression, chained comparisons also benefit from short-circuit evaluation — if the first comparison ('0 <= score') is already False, Python won't bother evaluating the second comparison at all.
Write a Python program that checks if a given number, 15, is divisible by both 3 and 5, printing 'FizzBuzz' if true, using the '%' modulus operator and the 'and' logical operator.
number = 15 if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") else: print("Not divisible by both 3 and 5") # Output: # FizzBuzz
What will be the output of the following code, and explain the reasoning based on the difference between '==' and 'is'? list1 = [10, 20, 30] list2 = [10, 20, 30] print(list1 == list2) print(list1 is list2)
The output will be: True False 'list1 == list2' returns True because '==' compares the actual VALUES contained within each list, and both lists happen to contain the identical sequence of elements (10, 20, 30). 'list1 is list2' returns False because 'is' checks OBJECT IDENTITY — even though their contents are equal, 'list1' and 'list2' were created as two separate, independent list objects, occupying different locations in memory, so they are not literally the 'same object', even though they are considered 'equal' by value.
Using the 'in' membership operator, write a Python program that checks whether the letter 'a' exists within the string "banana", and print an appropriate message.
word = "banana" if "a" in word: print("The letter 'a' is present in the word.") else: print("The letter 'a' is not present in the word.") # Output: # The letter 'a' is present in the word. # This works because the 'in' membership operator can be used directly on strings as well as lists, tuples, and dictionaries, checking whether the given substring exists anywhere within the target string.

Python operators — arithmetic, comparison, logical, membership, and identity — provide the fundamental tools for calculations, comparisons, and decision-making, with Python's distinctive readable word-based logical operators ('and', 'or', 'not') and unique membership ('in') and identity ('is') operators setting it apart from many other languages. Understanding the critical difference between '==' (value equality) and 'is' (object identity), along with true division versus floor division behavior, is essential for writing correct, idiomatic Python code and avoiding subtle bugs that trip up developers coming from other programming languages.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.