Skip to main content
Python for Beginners
CHAPTER 05 Beginner

Operators in Python

Updated: May 17, 2026
20 min read

# Operators in Python

Welcome to Chapter 5! Operators are the verbs of programming — they perform actions on data. Whether you're adding numbers, comparing values, or checking conditions, operators are involved. Python provides a rich set of operators that you'll use in virtually every program you write.

---

1. Introduction

An operator is a special symbol that performs an operation on one or more values (called operands). For example, in 5 + 3, the + is the operator and 5 and 3 are operands.

Real-World Analogy

Think of operators as actions in everyday life:
  • Addition (+) — Combining items in a shopping cart
  • Comparison (>) — Checking if your score is higher than the passing mark
  • Logical (and) — Both conditions must be true: "Is the store open AND do I have money?"

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use all arithmetic operators for mathematical calculations.
  • Compare values using comparison operators.
  • Use assignment operators for efficient variable updates.
  • Build complex conditions with logical operators.
  • Check membership in sequences using in and not in.
  • Understand identity operators is and is not.
  • Apply operator precedence correctly.

---

3. Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
//Floor Division10 // 33
%Modulus (Remainder)10 % 31
Exponentiation2 38

```python id="py5_ex1" a, b = 17, 5

print(f"Addition : {a} + {b} = {a + b}") # 22 print(f"Subtraction : {a} - {b} = {a - b}") # 12 print(f"Multiplication : {a} * {b} = {a * b}") # 85 print(f"Division : {a} / {b} = {a / b}") # 3.4 print(f"Floor Division : {a} // {b} = {a // b}") # 3 print(f"Modulus : {a} % {b} = {a % b}") # 2 print(f"Exponentiation : {a} {b} = {a b}") # 1419857

12
### Floor Division vs Regular Division

python id="py5_ex2" # Regular division always returns float print(10 / 3) # 3.3333333333333335 print(10 / 2) # 5.0 (still a float!)

# Floor division truncates to integer print(10 // 3) # 3 print(10 // 2) # 5

# With negative numbers (rounds toward negative infinity) print(-10 // 3) # -4 (not -3!) print(10 // -3) # -4

12
### Practical Use of Modulus

python id="py5ex3" # Check if a number is even or odd number = 42 if number % 2 == 0: print(f"{number} is EVEN") else: print(f"{number} is ODD")

# Get last digit of a number num = 12345 lastdigit = num % 10 print(f"Last digit of {num}: {lastdigit}") # 5

# Convert seconds to minutes and seconds totalseconds = 185 minutes = totalseconds // 60 seconds = totalseconds % 60 print(f"{total_seconds}s = {minutes}m {seconds}s") # 185s = 3m 5s

123456789101112131415
---

## 4. Comparison Operators

Comparison operators return `True` or `False`:

| Operator | Name | Example | Result |
|----------|------|---------|--------|
| `==` | Equal to | `5 == 5` | `True` |
| `!=` | Not equal to | `5 != 3` | `True` |
| `>` | Greater than | `5 > 3` | `True` |
| `<` | Less than | `5 < 3` | `False` |
| `>=` | Greater than or equal | `5 >= 5` | `True` |
| `<=` | Less than or equal | `5 <= 3` | `False` |

python id="py5_ex4" x, y = 10, 20

print(f"{x} == {y} → {x == y}") # False print(f"{x} != {y} → {x != y}") # True print(f"{x} > {y} → {x > y}") # False print(f"{x} < {y} → {x < y}") # True print(f"{x} >= {y} → {x >= y}") # False print(f"{x} <= {y} → {x <= y}") # True

12
### Chained Comparisons (Pythonic!)

python id="py5_ex5" # Python supports chained comparisons! age = 25 print(18 <= age <= 65) # True — is age between 18 and 65?

score = 85 print(80 < score < 90) # True — is score in the B range?

# Equivalent to (but cleaner than): print(18 <= age and age <= 65) # True

123456789101112131415
---

## 5. Assignment Operators

| Operator | Example | Equivalent |
|----------|---------|------------|
| `=` | `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` |
| `%=` | `x %= 3` | `x = x % 3` |
| `**=` | `x **= 3` | `x = x ** 3` |

python id="py5_ex6" # Assignment operators in action score = 100 print(f"Initial: {score}") # 100

score += 10 # Add 10 points print(f"After +10: {score}") # 110

score -= 5 # Subtract 5 points print(f"After -5: {score}") # 105

score *= 2 # Double the score print(f"After x2: {score}") # 210

score //= 3 # Floor divide by 3 print(f"After //3: {score}") # 70

123456789101112
> **Note:** Python does NOT have `++` or `--` operators like C/Java. Use `x += 1` instead.

---

## 6. Logical Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `and` | Both must be True | `True and False` → `False` |
| `or` | At least one must be True | `True or False` → `True` |
| `not` | Inverts the value | `not True` → `False` |

python id="py5ex7" age = 25 hasid = True hasticket = False

# AND — both conditions must be True canenter = age >= 18 and hasid print(f"Can enter (age & ID): {canenter}") # True

# OR — at least one condition must be True hasaccess = hasid or hasticket print(f"Has access: {hasaccess}") # True

# NOT — inverts the boolean print(f"Not hasticket: {not hasticket}") # True

12
### Truth Table

AND Truth Table: OR Truth Table: ┌───────┬───────┬──────┐ ┌───────┬───────┬──────┐ │ A │ B │ A∧B │ │ A │ B │ A∨B │ ├───────┼───────┼──────┤ ├───────┼───────┼──────┤ │ True │ True │ True │ │ True │ True │ True │ │ True │ False │ False│ │ True │ False │ True │ │ False │ True │ False│ │ False │ True │ True │ │ False │ False │ False│ │ False │ False │ False│ └───────┴───────┴──────┘ └───────┴───────┴──────┘

12
### Short-Circuit Evaluation

python id="py5_ex8" # Python stops evaluating as soon as the result is determined

# 'and' stops at the first False print(False and print("Won't execute")) # False — print() never runs

# 'or' stops at the first True print(True or print("Won't execute")) # True — print() never runs

# Practical use: safe division x = 0 result = x != 0 and 10 / x # Won't divide by zero! print(result) # False

1234567891011
---

## 7. Membership Operators

Check if a value exists in a sequence (string, list, tuple, set, dict):

| Operator | Description |
|----------|-------------|
| `in` | Returns True if value is found |
| `not in` | Returns True if value is NOT found |

python id="py5_ex9" # In strings message = "Hello, Python!" print("Python" in message) # True print("Java" in message) # False print("Java" not in message) # True

# In lists fruits = ["apple", "banana", "cherry"] print("banana" in fruits) # True print("grape" in fruits) # False print("grape" not in fruits) # True

# In dictionaries (checks keys, not values) student = {"name": "Alice", "age": 25} print("name" in student) # True print("Alice" in student) # False (checks keys!) print(25 in student.values()) # True (explicitly check values)

1234567891011
---

## 8. Identity Operators

Check if two variables refer to the **same object** in memory:

| Operator | Description |
|----------|-------------|
| `is` | Returns True if same object |
| `is not` | Returns True if different objects |

python id="py5_ex10" a = [1, 2, 3] b = [1, 2, 3] c = a

print(a == b) # True (same values) print(a is b) # False (different objects) print(a is c) # True (same object — c points to a) print(a is not b) # True

# Common use: checking for None result = None print(result is None) # True ✅ (recommended) print(result == None) # True (works but not recommended)

123456789101112131415
---

## 9. Bitwise Operators

Operate on individual bits of integers:

| Operator | Name | Example |
|----------|------|---------|
| `&` | AND | `5 & 3` → `1` |
| `\|` | OR | `5 \| 3` → `7` |
| `^` | XOR | `5 ^ 3` → `6` |
| `~` | NOT | `~5` → `-6` |
| `<<` | Left Shift | `5 << 1` → `10` |
| `>>` | Right Shift | `5 >> 1` → `2` |

python id="py5_ex11" a = 5 # Binary: 0101 b = 3 # Binary: 0011

print(f"a & b = {a & b}") # 1 (0001) print(f"a | b = {a | b}") # 7 (0111) print(f"a ^ b = {a ^ b}") # 6 (0110) print(f"~a = {~a}") # -6 print(f"a << 1 = {a << 1}") # 10 (1010) — multiply by 2 print(f"a >> 1 = {a >> 1}") # 2 (0010) — divide by 2

123456
---

## 10. Operator Precedence

Python follows mathematical order of operations:

Operator Precedence (Highest to Lowest): ┌────┬──────────────────────┬──────────┐ │ # │ Operator │ Example │ ├────┼──────────────────────┼──────────┤ │ 1 │ () Parentheses │ (2+3) │ │ 2 │ Exponentiation │ 23 │ │ 3 │ ~, +, - (Unary) │ -5 │ │ 4 │ *, /, //, % │ 2*3 │ │ 5 │ +, - (Binary) │ 2+3 │ │ 6 │ <<, >> (Shift) │ 5>>1 │ │ 7 │ & (Bitwise AND) │ 5&3 │ │ 8 │ ^ (Bitwise XOR) │ 5^3 │ │ 9 │ | (Bitwise OR) │ 5|3 │ │ 10 │ ==, !=, <, >, <=, >= │ 5>3 │ │ 11 │ not │ not True │ │ 12 │ and │ T and F │ │ 13 │ or │ T or F │ └────┴──────────────────────┴──────────┘

1

python id="py5_ex12" # Precedence examples result = 2 + 3 * 4 print(result) # 14 (not 20! multiplication first)

result = (2 + 3) * 4 print(result) # 20 (parentheses override precedence)

result = 2 3 2 print(result) # 512 (right-associative: 2 (32) = 2**9)

result = not True or False and True print(result) # False (not > and > or)

12345678910111213141516171819
---

## 11. Common Mistakes

1. **Using `=` instead of `==`:** `=` is assignment, `==` is comparison.
2. **Forgetting operator precedence:** Use parentheses to be explicit.
3. **Using `is` instead of `==` for value comparison:** `is` checks identity, not value.
4. **Integer division confusion:** `/` returns float, `//` returns int.
5. **Not understanding short-circuit evaluation:** Can cause subtle bugs.

---

## 12. Best Practices

- **Use parentheses** for clarity, even when not strictly needed.
- **Use `is` for None checks:** `x is None` not `x == None`.
- **Use `in` for membership tests** — it's readable and Pythonic.
- **Avoid complex boolean expressions** — break them into named variables.

python id="py5ex13" # ❌ Hard to read if age >= 18 and age <= 65 and hasid and (hasticket or isvip): pass

# ✅ Clear with named conditions isadult = 18 <= age <= 65 hasvalidaccess = hasticket or isvip canenter = isadult and hasid and hasvalidaccess ``

---

13. Exercises

  1. 1. Write a program that takes two numbers and prints all arithmetic operations.
  1. 2. Check if a number is divisible by both 3 and 5.
  1. 3. Write a program that determines if a year is a leap year.
  1. 4. Use membership operators to check if a character is a vowel.
  1. 5. Use bitwise operators to check if a number is even (hint: n & 1).

---

14. MCQs with Answers

Q1: What is the result of 10 // 3? A) 3.33 B) 3 C) 4 D) 3.0 Answer: B — Floor division truncates to integer.

Q2: What does 10 % 3 return? A) 3 B) 1 C) 0 D) 3.33 Answer: B — 10 divided by 3 has remainder 1.

Q3: What is True and False? A) True B) False C) None D) Error Answer: B

Q4: What is "hello" in "hello world"? A) True B) False C) Error D) None Answer: A — "hello" is a substring of "hello world".

Q5: What is 2 3 2? A) 64 B) 512 C) 36 D) 8 Answer: B — Exponentiation is right-associative: 2^(3^2) = 2^9 = 512.

Q6: Which operator checks if two variables point to the same object? A) == B) === C) is D) equals Answer: C

Q7: What is not not True? A) True B) False C) None D) Error Answer: A — Double negation returns original value.

Q8: What does += do? A) Assigns B) Adds and assigns C) Compares D) Increments by 1 Answer: B — x += 5 is equivalent to x = x + 5.

Q9: Does Python have ++ operator? A) Yes B) No Answer: B — Use x += 1 instead.

Q10: What is the output of 5 > 3 > 1? A) True B) False C) Error D) None Answer: A — Chained comparison: 5>3 AND 3>1, both True.

---

15. Interview Questions

  1. 1. What is the difference between / and // in Python?
*Answer:* / performs true division and always returns a float. // performs floor division and returns the largest integer less than or equal to the result.
  1. 2. Explain short-circuit evaluation in Python.
*Answer:* In
and, if the first operand is False, Python doesn't evaluate the second. In or, if the first operand is True, Python doesn't evaluate the second. This improves performance and prevents errors.
  1. 3. What is the difference between is and ==?
*Answer:* == compares values (equality). is compares identity (same object in memory). Use == for value comparison and is for None checks.
  1. 4. What is operator precedence in Python?
*Answer:* Operator precedence determines the order in which operators are evaluated. Parentheses have the highest precedence, followed by exponentiation, then multiplication/division, then addition/subtraction, then comparisons, then logical operators.
  1. 5. How does the walrus operator := work?
*Answer:* The walrus operator (Python 3.8+) assigns a value to a variable as part of an expression: if (n := len(data)) > 10: assigns len(data) to n and checks if it's > 10.

---

16. FAQs

Q: Does Python have a ternary operator? A: Yes! result = valueiftrue if condition else valueiffalse. Example: status = "pass" if score >= 60 else "fail".

Q: Can I chain comparison operators? A: Yes! 1 < x < 10 is valid and checks if x is between 1 and 10.

Q: What is the walrus operator? A: The := operator (Python 3.8+) assigns and returns a value in a single expression.

---

17. Summary

  • Arithmetic: +, -, *, /, //, %,
  • Comparison: ==, !=, >, <, >=, <=
  • Assignment: =, +=, -=, *=, /=, etc.
  • Logical: and, or, not
  • Membership: in, not in
  • Identity: is, is not
  • Bitwise: &, |, ^, ~, <<, >>`
  • Use parentheses when in doubt about precedence.

---

18. Next Chapter Recommendation

You've mastered operators! In Chapter 6: User Input and Output, you'll learn how to make your programs interactive** by taking input from users, formatting output beautifully, and building a user profile generator. Let's make your programs come alive! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·