Python Operators

Learn about different types of operators in Python and how to use them in your programs.

Python Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

print(10 + 5)

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

+
Addition
x + y
-
Subtraction
x - y
*
Multiplication
x * y
/
Division
x / y
%
Modulus
x % y
**
Exponentiation
x ** y
//
Floor division
x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

=
x = 5
x = 5
+=
x += 3
x = x + 3
-=
x -= 3
x = x - 3
*=
x *= 3
x = x * 3
/=
x /= 3
x = x / 3
%=
x %= 3
x = x % 3

Python Comparison Operators

Comparison operators are used to compare two values:

==
Equal
x == y
!=
Not equal
x != y
>
Greater than
x > y
<
Less than
x < y
>=
Greater than or equal to
x >= y
<=
Less than or equal to
x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

and
Returns True if both statements are true
x < 5 and x < 10
or
Returns True if one of the statements is true
x < 5 or x < 4
not
Reverse the result, returns False if the result is true
not(x < 5 and x < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

is
Returns True if both variables are the same object
x is y
is not
Returns True if both variables are not the same object
x is not y

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

in
Returns True if a sequence with the specified value is present in the object
x in y
not in
Returns True if a sequence with the specified value is not present in the object
x not in y

Operator Precedence

Operators evaluate in a fixed order, like maths. When in doubt, add parentheses for clarity.

PriorityOperators
Highest** (power)
* / // %
+ -
comparisons == != < >
not
and
Lowestor
print(2 + 3 * 4)      # 14, not 20  (* before +)
print((2 + 3) * 4)    # 20
print(2 ** 3 ** 2)    # 512  (** is right-associative: 2 ** 9)

is vs == : Identity vs Equality

== asks "are the values equal?"; is asks "are they the same object?". Use is only for None.

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)     # True  -> same contents
print(a is b)     # False -> different objects

x = None
print(x is None)  # True  -> the correct way to test for None

Never write if x == None; always use if x is None.

Chained Comparisons and Walrus

age = 25
print(18 <= age < 65)     # True  -> chained, reads like maths

# walrus := assigns inside an expression (Python 3.8+)
if (n := len("hello")) > 3:
    print(f"{n} characters")   # 5 characters

Try It Yourself

Exercise 1: Predict 10 - 2 * 3, then verify.

Show solution
print(10 - 2 * 3)   # 4  (multiplication first)

Exercise 2: Check whether a number n is between 1 and 10 (inclusive) using a chained comparison.

Show solution
n = 7
print(1 <= n <= 10)   # True

Key Takeaways

  • Know precedence: ** > * / > + - > comparisons > and > or.
  • == compares values; is compares identity (use for None).
  • Comparisons can chain: 1 <= n < 10.
  • Add parentheses whenever precedence is not obvious.

📘 Real-World Deep Dive

Python's operators are mostly familiar, but a few — <code>**</code>, <code>//</code>, <code>@</code>, walrus — shift how readable your code can be.

Real-Life Scenario

Compute compound interest with monthly contributions, using exponent, floor-division, and the walrus operator.

Real-Life Example

from decimal import Decimal, ROUND_HALF_UP

def yearly_balance(principal: Decimal, monthly: Decimal,
                   apr: Decimal, years: int) -> Decimal:
    monthly_rate = apr / 12
    months = years * 12
    factor = (1 + monthly_rate) ** months
    fv_lump = principal * factor
    fv_annuity = monthly * ((factor - 1) / monthly_rate)
    return (fv_lump + fv_annuity).quantize(Decimal("0.01"), ROUND_HALF_UP)

import sys
total = Decimal("0")
for line in sys.stdin:
    if (amt := Decimal(line.strip() or "0")) >= 0:
        total += amt
print("sum =", total.quantize(Decimal("0.01")), file=sys.stderr)

Expected Output

sum = 1250.00

Common mistakes

  • / on ints returns float in Python 3 — use // for true integer division or cast to Decimal.
  • -3 ** 2 is -9 because unary minus binds tighter than **; parenthesise: (-3) ** 2.
  • a is b is only equality for None, True, False, and small ints — everything else uses ==.

🚀 Performance & Best Practices

  • Chained comparison 0 < x < 10 is faster than 0 < x and x < 10 and more readable.
  • The matrix-multiplication operator A @ B dispatches to NumPy for arrays — use it instead of np.dot.
  • Walrus (:=) inside comprehensions and regex matches removes duplicate calls and clarifies intent.

🧪 Try It Yourself

  1. Add a --verbose path that prints monthly balances using the walrus to capture and re-use factor.
  2. Rewrite yearly_balance for yearly compounding and compare the result.
  3. Time for i in range(n): total += i vs. sum(range(n)); measure at n = 10² and n = 10⁶ and explain the difference.

FAQ: Python Operators

Common questions about this page.

What is Python Operators?

Python Operators is a Python Tutorial lesson that explains python operators in Python. Learn about different types of operators in Python and how to use them in your programs. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python operators examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python operators in this Python Tutorial Python lesson (Python Operators).

How do I use python operators in Python?

To use python operators in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python operators?

This Python Operators tutorial shows python operators syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Operators example for beginners

Yes. This page includes a beginner python operators example you can copy and run. It is designed for searches such as "python operators for beginners", "python operators example", and "how to use python operators".

What are common mistakes with python operators?

Common python operators mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python operators?

Python Operators is used in real Python work. Learning python operators helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Operators free to learn online?

Yes. You can learn python operators free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.