diff --git a/README.md b/README.md index 970a1db..1082ba8 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ flowchart LR | 01 | Python Basics | ✅ | ✅ | Complete | | 02 | Variables | ✅ | ✅ | Complete | | 03 | Data Types | ✅ | ✅ | Complete | -| 04 | Operators | 🚧 | 🚧 | Planned | +| 04 | Operators | ✅ | ✅ | Complete | | 05 | Control Flow | 🚧 | 🚧 | Planned | | 06 | Functions | 🚧 | 🚧 | Planned | | 07 | Modules | 🚧 | 🚧 | Planned | @@ -252,4 +252,3 @@ LeetCode: [aryanexe07](https://leetcode.com/aryanexe07) ![GitHub Stats](https://github-readme-stats.vercel.app/api?username=your-username&show_icons=true&theme=radical) ![Top Languages](https://github-readme-stats.vercel.app/api/top-langs/?username=your-username&layout=compact&theme=radical) - diff --git a/docs/04_operators/README.md b/docs/04_operators/README.md index 7aed729..4bb7444 100644 --- a/docs/04_operators/README.md +++ b/docs/04_operators/README.md @@ -1,47 +1,290 @@ # 04 · Operators -> 🚧 **Status: Planned.** This chapter's folder structure is in place; full content (theory, Mermaid diagrams, examples, best practices, common mistakes, interview questions, exercises) is being written in a follow-up pass, following the same format as chapters 01-03. - ## Introduction -_Coming soon._ +Operators are special symbols in Python that perform operations on one or more operands (values or variables). They are used for arithmetic calculations, comparisons, logical decisions, bit manipulation, membership testing, identity checking, and variable assignment. + +Python provides seven major categories of operators: + +- Arithmetic operators +- Comparison operators +- Logical operators +- Assignment operators +- Bitwise operators +- Membership operators +- Identity operators + +Understanding operators is fundamental because nearly every Python program relies on them. + +--- ## Theory -_Coming soon._ +Python operators can be classified as follows: + +```mermaid +flowchart TD + Operators --> Arithmetic + Operators --> Comparison + Operators --> Logical + Operators --> Assignment + Operators --> Bitwise + Operators --> Membership + Operators --> Identity + + Arithmetic --> Add["+ Addition"] + Arithmetic --> Sub["- Subtraction"] + Arithmetic --> Mul["* Multiplication"] + Arithmetic --> Div["/ Division"] + Arithmetic --> Floor["// Floor Division"] + Arithmetic --> Mod["% Modulus"] + Arithmetic --> Pow["** Exponentiation"] + + Comparison --> Eq["=="] + Comparison --> Ne["!="] + Comparison --> Gt[">"] + Comparison --> Lt["<"] + Comparison --> Ge[">="] + Comparison --> Le["<="] + + Logical --> And["and"] + Logical --> Or["or"] + Logical --> Not["not"] + + Assignment --> Assign["="] + Assignment --> PlusEq["+="] + Assignment --> MinusEq["-="] + Assignment --> MulEq["*="] + Assignment --> DivEq["/="] + + Bitwise --> Band["&"] + Bitwise --> Bor["|"] + Bitwise --> Bxor["^"] + Bitwise --> Bnot["~"] + Bitwise --> Lshift["<<"] + Bitwise --> Rshift[">>"] + + Membership --> In["in"] + Membership --> NotIn["not in"] + + Identity --> Is["is"] + Identity --> IsNot["is not"] +``` + +### Operator Categories + +- **Arithmetic operators** perform mathematical calculations. +- **Comparison operators** compare values and always return a boolean. +- **Logical operators** combine multiple boolean expressions. +- **Assignment operators** modify variable values. +- **Bitwise operators** manipulate individual bits of integers. +- **Membership operators** check whether an object exists inside another iterable. +- **Identity operators** determine whether two variables reference the exact same object in memory. + +--- ## Syntax -_Coming soon._ +```python +# Arithmetic +a + b +a - b +a * b +a / b +a // b +a % b +a ** b + +# Comparison +a == b +a != b +a > b +a < b +a >= b +a <= b + +# Logical +x and y +x or y +not x + +# Assignment +x += 1 +x -= 1 +x *= 2 +x /= 2 + +# Bitwise +a & b +a | b +a ^ b +~a +a << 2 +a >> 2 + +# Membership +"x" in text +"x" not in text + +# Identity +a is b +a is not b +``` + +--- ## Examples -See [`src/04_operators/`](../../src/04_operators/). +See [`src/04_operators/operators_demo.py`](../../src/04_operators/operators_demo.py). + +--- ## Code Explanation -_Coming soon._ +### Arithmetic Operators + +Used to perform mathematical operations. + +```python +5 + 3 +5 ** 3 +5 // 3 +``` + +### Comparison Operators + +Return either `True` or `False`. + +```python +5 > 3 +5 == 3 +``` + +### Logical Operators + +Operate on boolean expressions. + +```python +True and False +True or False +not True +``` + +Although Python allows expressions like `5 and 3`, they return one of the operands rather than a boolean. For beginners, use logical operators with boolean values. + +### Assignment Operators + +A shorthand for updating variables. + +```python +x += 5 +``` + +is equivalent to + +```python +x = x + 5 +``` + +### Bitwise Operators + +Operate on the binary representation of integers. + +Example: + +```text +5 = 0101 +3 = 0011 + +5 & 3 = 0001 +5 | 3 = 0111 +5 ^ 3 = 0110 +``` + +These are commonly used in low-level programming, networking, graphics, and optimization. + +### Membership Operators + +Check whether a value exists inside a sequence. + +```python +"cat" in "concatenate" +3 in [1, 2, 3] +``` + +### Identity Operators + +Identity checks whether two variables point to the same object. + +```python +a = [1,2] +b = a +c = [1,2] + +a is b # True +a is c # False + +a == c # True +``` + +`is` compares object identity, while `==` compares values. + +--- ## Best Practices -_Coming soon._ +- Use `==` for value comparison and reserve `is` for checking against `None`. +- Prefer logical operators with boolean expressions for readability. +- Use compound assignment (`+=`, `*=`, etc.) when updating variables. +- Use parentheses when combining multiple operators to improve readability. +- Avoid unnecessary bitwise operations unless they clearly solve the problem. + +--- ## Common Mistakes -_Coming soon._ +| Mistake | Why it's a problem | Fix | +|----------|--------------------|-----| +| Using `is` instead of `==` | `is` compares object identity, not values | Use `==` for value comparison | +| Assuming `and` always returns `True` or `False` | It returns one of its operands | Use boolean expressions | +| Confusing `/` with `//` | `/` returns a float, `//` performs floor division | Choose the correct operator | +| Using `=` inside conditions | `=` assigns instead of compares | Use `==` | +| Using bitwise operators instead of logical operators | `&` and `|` are different from `and` and `or` | Use the appropriate operator | + +--- ## Interview Questions -_Coming soon._ +1. What is the difference between `==` and `is`? +2. Explain the difference between `/` and `//`. +3. What is short-circuit evaluation in logical operators? +4. What is the difference between `and` and `&`? +5. When would you use bitwise operators in real-world applications? +6. Why does `5 and 3` evaluate to `3`? +7. Explain operator precedence in Python. + +--- ## Exercises -_Coming soon._ +1. Write a program that demonstrates every arithmetic operator. +2. Compare two numbers using every comparison operator. +3. Create a calculator using arithmetic operators. +4. Demonstrate the difference between `==` and `is`. +5. Convert two integers to binary and manually verify the results of `&`, `|`, and `^`. +6. Write a program that checks whether a word exists inside a sentence. +7. Demonstrate short-circuit evaluation using logical operators. + +--- ## Further Reading -- [Python official documentation](https://docs.python.org/3/) +- https://docs.python.org/3/reference/expressions.html +- https://docs.python.org/3/library/operator.html + +--- ## Related Topics -- [Chapter Directory](../../README.md#-chapter-directory) +- [03 · Data Types](../03_data_types/README.md) +- [05 · Conditional Statements](../05_conditionals/README.md) diff --git a/src/04_operators/example.py b/src/04_operators/example.py deleted file mode 100644 index a4c7242..0000000 --- a/src/04_operators/example.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Chapter 04 · Operators — placeholder. - -This chapter's runnable examples are planned but not yet written. -Track progress in the repository root README.md Progress Tracker. -""" - - -def main() -> None: - print("Chapter 04 (Operators) examples: coming soon.") - - -if __name__ == "__main__": - main() diff --git a/src/04_operators/operators.py b/src/04_operators/operators.py new file mode 100644 index 0000000..ec38f23 --- /dev/null +++ b/src/04_operators/operators.py @@ -0,0 +1,151 @@ +""" +Chapter 04 · Operators + +Today we will learn about operators in Python. + +Operators are special symbols used to perform operations on values and variables. + +Python provides the following categories of operators: + + • Arithmetic Operators + • Comparison Operators + • Logical Operators + • Assignment Operators + • Bitwise Operators + • Membership Operators + • Identity Operators +""" + + +def main() -> None: + # -------------------------------------------------- + # Arithmetic Operators + # -------------------------------------------------- + print("=== Arithmetic Operators ===") + + a = 10 + b = 3 + + print(f"{a} + {b} =", a + b) # Addition + print(f"{a} - {b} =", a - b) # Subtraction + print(f"{a} * {b} =", a * b) # Multiplication + print(f"{a} / {b} =", a / b) # Division + print(f"{a} // {b} =", a // b) # Floor Division + print(f"{a} % {b} =", a % b) # Modulus + print(f"{a} ** {b} =", a**b) # Exponentiation + + print() + + # -------------------------------------------------- + # Comparison Operators + # -------------------------------------------------- + print("=== Comparison Operators ===") + + 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() + + # -------------------------------------------------- + # Logical Operators + # -------------------------------------------------- + print("=== Logical Operators ===") + + x = True + y = False + + print("True and False ->", x and y) + print("True or False ->", x or y) + print("not True ->", not x) + + print() + + # -------------------------------------------------- + # Assignment Operators + # -------------------------------------------------- + print("=== Assignment Operators ===") + + num = 10 + print("Initial value:", num) + + num += 5 + print("After += 5 :", num) + + num -= 3 + print("After -= 3 :", num) + + num *= 2 + print("After *= 2 :", num) + + num /= 4 + print("After /= 4 :", num) + + num %= 3 + print("After %= 3 :", num) + + num **= 2 + print("After **= 2:", num) + + num //= 2 + print("After //= 2:", num) + + print() + + # -------------------------------------------------- + # Bitwise Operators + # -------------------------------------------------- + print("=== Bitwise Operators ===") + + a = 5 # 0101 + b = 3 # 0011 + + print(f"{a} & {b} =", a & b) + print(f"{a} | {b} =", a | b) + print(f"{a} ^ {b} =", a ^ b) + print(f"~{a} =", ~a) + print(f"{a} << 1 =", a << 1) + print(f"{a} >> 1 =", a >> 1) + + print() + + # -------------------------------------------------- + # Membership Operators + # -------------------------------------------------- + print("=== Membership Operators ===") + + text = "Python Programming" + + print("'Python' in text ->", "Python" in text) + print("'Java' in text ->", "Java" in text) + print("'Java' not in text ->", "Java" not in text) + + numbers = [1, 2, 3, 4, 5] + + print("3 in numbers ->", 3 in numbers) + print("10 not in numbers ->", 10 not in numbers) + + print() + + # -------------------------------------------------- + # Identity Operators + # -------------------------------------------------- + print("=== Identity Operators ===") + + list1 = [1, 2, 3] + list2 = list1 + list3 = [1, 2, 3] + + print("list1 is list2 ->", list1 is list2) + print("list1 is list3 ->", list1 is list3) + + print("list1 == list3 ->", list1 == list3) + + print("list1 is not list3 ->", list1 is not list3) + + +if __name__ == "__main__": + main()