Back to Home 24 lessons Pyodide ready

Python Operators
The Language of Logic & Math

Master every operator in Python: arithmetic, comparison, logical, assignment, bitwise, membership, and identity. Learn how to manipulate data and control program flow. 24 interactive lessons with runnable code โ€” crafted by @PoeticGlenn.

What you will learn

Everything about operators in Python โ€” from basic arithmetic and comparisons to advanced bitwise operations and identity checks. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.

Why Operators Are the Building Blocks of Code

Operators are the fundamental tools that allow you to perform calculations, compare values, make decisions, and manipulate data. Without operators, you couldn't add numbers, check conditions, or assign variables. This curriculum, designed by @PoeticGlenn, covers every operator type in Python โ€” from the familiar arithmetic operators to the powerful bitwise and identity operators that give you fine-grained control over your code.

Mathematical Power

Arithmetic operators let you perform calculations, from simple addition to exponentiation and modulo.

Control Flow

Comparison and logical operators are essential for conditionals and loops โ€” they control your program's logic.

Low-Level Manipulation

Bitwise operators work at the binary level, giving you performance and control for systems programming and optimization.

"Operators are the verbs of programming languages. They make things happen." โ€” @PoeticGlenn ๐Ÿ

Operators Are in Every Single Python Program

Every time you write a condition, calculate a value, or assign a variable, you're using operators. Understanding them thoroughly is non-negotiable for any Python developer. This curriculum, curated by @PoeticGlenn, ensures you know not just what each operator does, but when and why to use it.

๐Ÿงฎ Mathematical Foundation

Arithmetic and assignment operators are the most frequently used. Master them to write concise, readable, and efficient numeric code.

โš–๏ธ Decision Making

Comparison and logical operators let your program make decisions. They are the foundation of if statements and loops.

๐Ÿ–ฅ๏ธ Systems & Performance

Bitwise operators are essential for working with flags, permissions, and low-level data. They are the language of systems programming.

๐Ÿ” Precision & Clarity

Membership and identity operators make your code more expressive and precise, letting you check existence and object equality cleanly.

@PoeticGlenn says: "Operators are the punctuation of code. Just like commas and periods in writing, they structure the logic and flow of your programs."

Why Operator Mastery Separates Experts from Beginners

In every programming language, operators are the tools that manipulate data and control execution. Python's operator set is rich and intuitive, but using them effectively requires a deep understanding. This curriculum, designed by @PoeticGlenn, gives you the expertise to write clean, performant, and expressive Python code that stands up to professional standards.

Data Processing

From filtering data with comparison operators to transforming it with arithmetic, operators are the core of data processing.

Security & Validation

Membership and identity operators help you validate input, check permissions, and ensure data integrity.

Systems Programming

Bitwise operators give you the tools to work with binary data, flags, and packed integers โ€” essential for performance-critical applications.

The operators you master today will empower every line of code you write tomorrow.

โž• Arithmetic Operators

Perform mathematical operations on numbers.

๐Ÿ“ 1.1 Arithmetic Operators Overview

Python supports all standard arithmetic operators: +, -, *, /, //, %, **.

Step-by-step explanation:

  • Step 1: Addition: 10 + 3 adds two numbers.
  • Step 2: Subtraction: 10 - 3 subtracts the second from the first.
  • Step 3: Multiplication: 10 * 3 multiplies two numbers.
  • Step 4: Division: 10 / 3 returns a float.
  • Step 5: Floor division: 10 // 3 returns the integer quotient.
  • Step 6: Modulo: 10 % 3 returns the remainder.
  • Step 7: Exponentiation: 10 ** 3 raises to a power.
python
a, b = 10, 3

print(f"a + b = {a + b}")
print(f"a - b = {a - b}")
print(f"a * b = {a * b}")
print(f"a / b = {a / b}")
print(f"a // b = {a // b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")
๐Ÿ’ก Division / always returns a float. Use // for integer division.

๐Ÿ“ 1.2 Modulo Operator (%)

The modulo operator returns the remainder of a division. It's useful for checking divisibility and cycling through ranges.

Step-by-step explanation:

  • Step 1: Check if a number is even: num % 2 == 0.
  • Step 2: Get the last digit: num % 10.
  • Step 3: Cycle through a range: index % 3 gives 0, 1, 2, 0, 1, 2...
python
num = 17

print(f"num % 2 = {num % 2}")
print(f"{num} is even: {num % 2 == 0}")

print(f"num % 10 = {num % 10}")

for i in range(6):
    print(f"{i} % 3 = {i % 3}")

โš–๏ธ Comparison Operators

Compare values and return True or False.

๐Ÿ“ 2.1 Comparison Operators Overview

Python supports: ==, !=, >, <, >=, <=.

Step-by-step explanation:

  • Step 1: Equal to: x == y checks if values are equal.
  • Step 2: Not equal: x != y checks if values are different.
  • Step 3: Greater than: x > y.
  • Step 4: Less than: x < y.
  • Step 5: Greater than or equal to: x >= y.
  • Step 6: Less than or equal to: x <= y.
python
x, y = 5, 10

print(f"x == y: {x == y}")
print(f"x != y: {x != y}")
print(f"x > y: {x > y}")
print(f"x < y: {x < y}")
print(f"x >= y: {x >= y}")
print(f"x <= y: {x <= y}")
๐Ÿ’ก Comparison operators are used in if statements and loops to control program flow.

๐Ÿ“ 2.2 Chaining Comparisons

Python allows chaining comparisons: a < b < c is equivalent to a < b and b < c.

Step-by-step explanation:

  • Step 1: Chain comparisons for cleaner code.
  • Step 2: Check if a value is within a range.
python
x = 5

print(f"1 < x < 10: {1 < x < 10}")
print(f"0 <= x <= 10: {0 <= x <= 10}")

print(f"(1 < x) and (x < 10): {(1 < x) and (x < 10)}")

๐Ÿ”€ Logical Operators

Combine boolean values: and, or, not.

๐Ÿ“ 3.1 Logical Operators Overview

Logical operators are used to combine conditional statements.

Step-by-step explanation:

  • Step 1: and returns True if both operands are true.
  • Step 2: or returns True if at least one operand is true.
  • Step 3: not returns the opposite boolean value.
python
a, b = True, False

print(f"a and b: {a and b}")
print(f"a or b: {a or b}")
print(f"not a: {not a}")

x, y = 5, 10
print(f"x > 3 and y < 20: {x > 3 and y < 20}")
print(f"x > 10 or y > 5: {x > 10 or y > 5}")
๐Ÿ’ก Logical operators short-circuit: and stops at the first False, or stops at the first True.

โœ๏ธ Assignment Operators

Assign values to variables, often combined with arithmetic.

๐Ÿ“ 4.1 Assignment Operators Overview

Python supports: =, +=, -=, *=, /=, %=, //=, **=.

Step-by-step explanation:

  • Step 1: x = 10 assigns the value 10.
  • Step 2: x += 5 is equivalent to x = x + 5.
  • Step 3: x *= 2 is equivalent to x = x * 2.
python
x = 10
print(f"x = {x}")

x += 3
print(f"x += 3 โ†’ x = {x}")

x -= 5
print(f"x -= 5 โ†’ x = {x}")

x *= 2
print(f"x *= 2 โ†’ x = {x}")

x /= 4
print(f"x /= 4 โ†’ x = {x}")

x //= 2
print(f"x //= 2 โ†’ x = {x}")

x **= 2
print(f"x **= 2 โ†’ x = {x}")

๐Ÿ’ป Bitwise Operators

Work with numbers at the binary level: &, |, ^, ~, <<, >>.

๐Ÿ“ 5.1 Bitwise Operators Overview

Bitwise operators are used for low-level manipulation of integer bits.

Step-by-step explanation:

  • Step 1: & (AND): 1 if both bits are 1.
  • Step 2: | (OR): 1 if at least one bit is 1.
  • Step 3: ^ (XOR): 1 if bits are different.
  • Step 4: ~ (NOT): Inverts all bits.
  • Step 5: << (Left shift): Shifts bits left.
  • Step 6: >> (Right shift): Shifts bits right.
python
a, b = 6, 3

print(f"a = {a} (binary: {bin(a)})")
print(f"b = {b} (binary: {bin(b)})")
print(f"a & b = {a & b} ({bin(a & b)})")
print(f"a | b = {a | b} ({bin(a | b)})")
print(f"a ^ b = {a ^ b} ({bin(a ^ b)})")
print(f"~a = {~a} ({bin(~a)})")
print(f"a << 1 = {a << 1} ({bin(a << 1)})")
print(f"a >> 1 = {a >> 1} ({bin(a >> 1)})")

๐Ÿ“ 5.2 Practical Use: Flags

Bitwise operators are commonly used to manage flags and permissions.

Step-by-step explanation:

  • Step 1: Define flags: READ = 1, WRITE = 2, EXEC = 4.
  • Step 2: Combine flags using |: READ | WRITE.
  • Step 3: Check if a flag is set using &.
python
READ = 1
WRITE = 2
EXEC = 4

permissions = READ | WRITE
print(f"permissions: {permissions} (binary: {bin(permissions)})")

if permissions & READ:
    print("Read permission granted")
if permissions & WRITE:
    print("Write permission granted")
if permissions & EXEC:
    print("Execute permission granted")
else:
    print("Execute permission NOT granted")
Advertisement

๐Ÿ” Membership Operators

Check if a value exists in a sequence: in, not in.

๐Ÿ“ 6.1 Membership Operators Overview

Membership operators are used to test if a value is present in a list, tuple, string, or other collection.

Step-by-step explanation:

  • Step 1: in returns True if the value is found.
  • Step 2: not in returns True if the value is not found.
python
fruits = ["apple", "banana", "cherry"]

print(f"'apple' in fruits: {'apple' in fruits}")
print(f"'grape' in fruits: {'grape' in fruits}")
print(f"'grape' not in fruits: {'grape' not in fruits}")

text = "Hello, world!"
print(f"'world' in text: {'world' in text}")
print(f"'Python' in text: {'Python' in text}")

๐Ÿ†” Identity Operators

Compare object identity: is, is not.

๐Ÿ“ 7.1 Identity Operators Overview

Identity operators check if two variables refer to the same object in memory.

Step-by-step explanation:

  • Step 1: is returns True if both variables point to the same object.
  • Step 2: is not returns True if they point to different objects.
  • Step 3: == compares values, is compares identity.
python
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(f"a = {a}, id(a): {id(a)}")
print(f"b = {b}, id(b): {id(b)}")
print(f"c = {c}, id(c): {id(c)}")

print(f"a is b: {a is b}")
print(f"a is c: {a is c}")
print(f"a == c: {a == c}")

x = 10
y = 10
print(f"x is y (integers): {x is y}")
โš ๏ธ Use is for None, booleans, and checking object identity. Use == for value comparisons.

๐Ÿ“Š Operator Precedence

Python follows specific rules to determine the order in which operators are evaluated.

๐Ÿ“ 8.1 Precedence Rules

Use parentheses to make your code explicit and avoid confusion.

Step-by-step explanation:

  • Step 1: Exponentiation has the highest precedence among arithmetic operators.
  • Step 2: Multiplication and division are evaluated before addition and subtraction.
  • Step 3: Comparison operators have lower precedence than arithmetic.
  • Step 4: Logical operators have lower precedence than comparisons.
  • Step 5: Use parentheses to override default precedence.
python
print("Without parentheses:")
print(f"10 + 5 * 2 = {10 + 5 * 2}")
print(f"(10 + 5) * 2 = {(10 + 5) * 2}")

print("\nComparison and logical:")
x, y, z = 5, 10, 15
print(f"x < y and y < z: {x < y and y < z}")
print(f"x < y and y > z: {x < y and y > z}")
print(f"x < y or y > z: {x < y or y > z}")
๐Ÿ’ก When in doubt, use parentheses! They make your intention clear and improve readability.

โ“ Frequently Asked Questions โ€” Python Operators

Common questions about operators in Python, answered.

What is the difference between == and is?

+

== compares the values of two objects, while is checks if they refer to the same object in memory. Use == for value equality, and is for identity (e.g., None).

What does the % operator do?

+

The modulo operator % returns the remainder of a division. For example, 10 % 3 returns 1. It's useful for checking divisibility, cycling through ranges, and extracting digits.

What are bitwise operators used for?

+

Bitwise operators work at the binary level. They are used for low-level programming, flag manipulation, permissions, packing data, and optimization.

What is operator precedence?

+

Operator precedence determines the order in which operators are evaluated in an expression. For example, multiplication is evaluated before addition. Use parentheses to override the default precedence.

What is short-circuit evaluation?

+

In logical expressions, Python stops evaluating as soon as the result is known. For and, if the first operand is False, it doesn't evaluate the second. For or, if the first operand is True, it doesn't evaluate the second.

Can I use operators with strings?

+

Yes! + concatenates strings, * repeats strings, and in checks for substring membership. Comparison operators work lexicographically.

What is the difference between / and //?

+

/ performs floating-point division and always returns a float. // performs floor division and returns the integer quotient, discarding the remainder.

๐Ÿ’› You've Mastered Python Operators

From arithmetic and comparisons to logical, bitwise, membership, and identity operators โ€” you now have a complete understanding of Python's operator ecosystem. You know how to perform calculations, make decisions, manipulate data at the binary level, and write expressive, efficient code.

This curriculum, crafted by @PoeticGlenn, is your definitive guide to operators in Python. Whether you're building algorithms, analyzing data, or optimizing performance, you have the tools to succeed.

24 lessons 20+ code examples 1.1k+ learners

"Operators are the verbs of programming. Master them, and you can express any algorithm." โ€” Glenn Junsay Pansensoy (@PoeticGlenn)

Advertisement