Operators in Python
# 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
inandnot in.
-
Understand identity operators
isandis not.
- Apply operator precedence correctly.
---
3. Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3.333... |
// | Floor Division | 10 // 3 | 3 |
% | Modulus (Remainder) | 10 % 3 | 1 |
| Exponentiation | 2 3 | 8 |
```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
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
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
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
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
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
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
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│ └───────┴───────┴──────┘ └───────┴───────┴──────┘
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
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)
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)
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
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 │ └────┴──────────────────────┴──────────┘
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)
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. Write a program that takes two numbers and prints all arithmetic operations.
- 2. Check if a number is divisible by both 3 and 5.
- 3. Write a program that determines if a year is a leap year.
- 4. Use membership operators to check if a character is a vowel.
-
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.
What is the difference between /
and//in Python?
performs true division and always returns a float. // performs floor division and returns the largest integer less than or equal to the result.
-
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.
-
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.
-
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.
-
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
---
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! 🚀