diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/01-arithmetic-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/01-arithmetic-operators.md deleted file mode 100644 index 7b8481a8c..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/01-arithmetic-operators.md +++ /dev/null @@ -1,338 +0,0 @@ ---- -title: "Arithmetic Operators — Doing Math with Python" -chapter: 15 -lesson: 1 -duration_minutes: 50 - -# HIDDEN SKILLS METADATA (Institutional Integration Layer) -skills: - - name: "Arithmetic Operations with Type Safety" - proficiency_level: "A1-A2" - category: "Technical" - bloom_level: "Understand" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can write `result: int = 5 + 3` and use `type(result)` to verify result type; perform all 7 arithmetic operations without referencing examples" - - - name: "Understanding Type Hint Feedback from Operations" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Understand" - digcomp_area: "Digital Content Creation" - measurable_at_this_level: "Student can explain 'Why does int / int give float?' and 'Why does int // int give int?' using type validation" - - - name: "AI-Driven Exploration of Edge Cases" - proficiency_level: "A2" - category: "Soft" - bloom_level: "Apply" - digcomp_area: "Communication & Collaboration" - measurable_at_this_level: "Student can formulate questions like 'What happens if I divide by zero?' and validate AI responses through code testing" - -learning_objectives: - - objective: "Understand what each of the seven arithmetic operators (+, -, *, /, //, %, **) does in plain language" - proficiency_level: "A1" - bloom_level: "Understand" - assessment_method: "Explanation of operators; code with type verification" - - - objective: "Apply arithmetic operators correctly to perform calculations using type hints and validation" - proficiency_level: "A2" - bloom_level: "Apply" - assessment_method: "Write arithmetic expressions without errors; use type() to verify results" - -cognitive_load: - new_concepts: 5 - assessment: "5 new concepts (the 7 operators grouped as arithmetic family, type behavior with int/float, division differences, modulo for remainders, exponentiation) within A1-A2 limit of 5 ✓" - -differentiation: - extension_for_advanced: "Explore operator precedence with complex expressions; ask AI about edge cases like 0.1 + 0.2; investigate negative number behavior with modulo and floor division" - remedial_for_struggling: "Focus on first 4 operators (+, -, *, /); use concrete single-digit numbers; build confidence with simple expressions before advancing to //, %, **" - -# Generation metadata -generated_by: "content-implementer v3.0.0" -source_spec: "specs/part-4-chapter-17/spec.md" -created: "2025-11-08" -last_modified: "2025-11-08" -git_author: "Claude Code" -workflow: "content-implementer subagent" -version: "1.0.0" ---- - -# Arithmetic Operators — Doing Math with Python - -You've been doing math your whole life. Five plus three equals eight. Ten minus four equals six. Now you're going to do the exact same math with Python—except Python calls them **operators** instead of just "math". - -An **operator** is a symbol that tells Python to do something with values. In this lesson, you'll learn the seven arithmetic operators that let you perform calculations. You already know the concepts; Python just has its own symbols for them. - -## What It Is: Operators as Verbs for Numbers - -Think of operators like verbs in English. Just like "run", "jump", and "walk" are actions, operators are actions you perform on numbers. - -Python has **seven arithmetic operators**: - -- `+` **Addition** — combines values -- `-` **Subtraction** — finds the difference -- `*` **Multiplication** — scales values -- `/` **Division** — splits into parts -- `//` **Floor division** — counts whole groups (no decimals) -- `%` **Modulus** — finds the remainder -- `**` **Exponentiation** — raises to a power - -All of these do exactly what you learned in math class. The difference is that Python needs to know what to do with types—and that's where it gets interesting. - -## The Seven Arithmetic Operators - -Let's see all seven operators in action. Each one takes two numbers (called **operands**) and produces a result. - -### Addition and Subtraction: The Basics - -```python -# Arithmetic operators: doing math with Python -x: int = 10 -y: int = 3 - -# Addition: combine values -add_result: int = x + y -print(f"{x} + {y} = {add_result}") # 10 + 3 = 13 - -# Subtraction: find the difference -sub_result: int = x - y -print(f"{x} - {y} = {sub_result}") # 10 - 3 = 7 -``` - -Both addition and subtraction keep the type consistent. When you add two integers, you get an integer back. Same with subtraction. - -#### 💬 AI Colearning Prompt - -> "Python is designed to be helpful with numbers. But why does Python have both `/` and `//` for division when math just has one division symbol? Explain the difference and why this matters." - -Notice something: we're asking AI to explain the **design choice** behind operators, not just what they do. That's more useful than memorization. - -### Multiplication, Division, and Floor Division - -```python -# Continuing from previous example (x=10, y=3) -x: int = 10 -y: int = 3 - -# Multiplication: scaling -mul_result: int = x * y -print(f"{x} * {y} = {mul_result}") # 10 * 3 = 30 - -# Division: splits into parts (always float) -div_result: float = x / y -print(f"{x} / {y} = {div_result}") # 10 / 3 = 3.3333... - -# Floor division: counts whole groups (integer result) -floor_result: int = x // y -print(f"{x} // {y} = {floor_result}") # 10 // 3 = 3 -``` - -Here's something important: **division with `/` always returns a float, even when both numbers are integers**. This surprises many beginners because they expect `10 / 5` to give `2` (an int), but it actually gives `2.0` (a float). - -Why? Because division often produces decimals, so Python designed `/` to always return float. If you want an integer result (discarding the decimal), you use `//` (floor division). - -#### 🎓 Expert Insight - -> In AI-native development, you don't memorize why Python made this choice. You understand what's happening (division produces floats, floor division gives integers) and use the right operator for your intent. Then you verify with `type()` to be sure. - -Let's verify this with `type()`: - -```python -# Continuing from previous example (x=10, y=3) -x: int = 10 -y: int = 3 - -# Calculate results -div_result: float = x / y -floor_result: int = x // y - -# Verify the types -print(f"Type of 10 / 3: {type(div_result)}") # -print(f"Type of 10 // 3: {type(floor_result)}") # - -# What if we use floor division with floats? -f1: float = 10.5 -f2: float = 3.0 -float_floor: float = f1 // f2 -print(f"Type of 10.5 // 3.0: {type(float_floor)}") # (not int!) -``` - -Notice: when you floor divide two floats, the result is still a float. Python follows this rule: **if either operand is a float, the result is a float**. - -### Modulus: The Remainder Operator - -```python -# Continuing from previous example (x=10, y=3) -x: int = 10 -y: int = 3 - -# Modulus: finds the remainder -mod_result: int = x % y -print(f"{x} % {y} = {mod_result}") # 10 % 3 = 1 -# (10 divided by 3 is 3 with remainder 1) -``` - -The modulus operator `%` is useful when you care about what's left over. For example: -- Check if a number is even: `5 % 2` gives 1 (odd), `4 % 2` gives 0 (even) -- Find the last digit: `234 % 10` gives 4 -- Cycle through values: `7 % 3` gives 1, `8 % 3` gives 2, `9 % 3` gives 0 (then it repeats) - -### Exponentiation: Raising to a Power - -```python -# Continuing from previous example (x=10) -x: int = 10 - -# Exponentiation: raising to a power -exp_result: int = x ** 2 -print(f"{x} ** 2 = {exp_result}") # 10 ** 2 = 100 - -# More examples -print(f"2 ** 3 = {2 ** 3}") # 8 (2 × 2 × 2) -print(f"5 ** 0 = {5 ** 0}") # 1 (anything to the 0th power is 1) -print(f"2 ** 10 = {2 ** 10}") # 1024 (exponents grow fast!) -``` - -Notice the symbol: `**` (two asterisks), not `^`. The caret symbol `^` does something different in Python (bitwise XOR), so don't use it for exponentiation. - -#### 🤝 Practice Exercise - -> **Ask your AI**: "I understand that arithmetic operators in Python are +, -, *, /, //, %, **. But why does `/` always return a float even when dividing two integers? And when would I actually use `//` vs. `/`? Give me a concrete example where using the wrong one would cause a bug." - -**Expected Outcome**: You'll understand the design decisions behind Python's division operators and how they interact with types. - -## Type Behavior: Why Types Change - -Here's where it gets interesting. When you combine operands of different types, Python follows rules about what type the result is. - -```python -# All integer operations -int_add: int = 5 + 3 # 8 (int) -int_mult: int = 5 * 3 # 15 (int) - -# Division always gives float -int_div: float = 5 / 2 # 2.5 (float) - -# Mixing int and float -mixed: float = 5 + 2.0 # 7.0 (float) - float "wins" -mixed2: float = 5 * 2.5 # 12.5 (float) - -# Verify with type() -print(type(int_add)) # -print(type(int_div)) # -print(type(mixed)) # -``` - -**The pattern**: When you mix `int` and `float`, the result is always `float`. Python considers this safe because a float can represent any integer value (though with potential precision loss for very large numbers). - -## Operator Precedence: Order Matters - -Just like in math, operators have an **order of operations**. Multiplication happens before addition. - -```python -# Wrong order: 2 + 3 * 4 -result1: int = 2 + 3 * 4 -print(result1) # 14 (not 20!) -# Python evaluates: 3 * 4 = 12, then 2 + 12 = 14 - -# Use parentheses to control order -result2: int = (2 + 3) * 4 -print(result2) # 20 (addition happens first) -``` - -Python follows PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). But honestly, **the best practice is to use parentheses**. Make your intent clear. - -```python -# Real-world example: calculating total with tax -price: float = 100.0 -tax_rate: float = 0.08 -fee: float = 10.0 - -# Without parentheses, this is confusing -total1: float = price * (1 + tax_rate) + fee # 118.0 (tax then fee) - -# The parentheses make it obvious: first multiply by (1 + 0.08), then add fee -total2: float = (price * (1 + tax_rate)) + fee # 118.0 (same result, clearer intent) -``` - -Parentheses aren't just for changing order—they're for **clarifying your intent** to anyone reading your code (including yourself a month from now). - -#### 💬 AI Colearning Prompt - -> "When I see `2 + 3 * 4`, how does Python know to do multiplication first? Explain operator precedence. And when should I use parentheses even if they're not required?" - -## Putting It Together: A Complete Example - -Let's see all seven operators working together: - -```python -# Working with arithmetic operators -x: int = 20 -y: int = 7 - -# All seven operators -print(f"Addition: {x} + {y} = {x + y}") # 27 -print(f"Subtraction: {x} - {y} = {x - y}") # 13 -print(f"Multiplication: {x} * {y} = {x * y}") # 140 -print(f"Division: {x} / {y} = {x / y}") # 2.857... -print(f"Floor division: {x} // {y} = {x // y}") # 2 -print(f"Modulus: {x} % {y} = {x % y}") # 6 (remainder when 20 ÷ 7) -print(f"Exponentiation: {x} ** 2 = {x ** 2}") # 400 (20 squared) - -# Verify types -print(f"\nType verification:") -print(f"Type of {x} + {y}: {type(x + y)}") # -print(f"Type of {x} / {y}: {type(x / y)}") # -print(f"Type of {x} // {y}: {type(x // y)}") # -``` - -This example shows: -- All seven operators working -- Different types in the results (int vs. float) -- Type verification with `type()` - -## Common Mistakes (And Why They Happen) - -**Mistake 1: Expecting `5 / 2` to give `2`** - -```python -result: float = 5 / 2 # Gives 2.5, not 2 -# Use // if you want an integer result -result_int: int = 5 // 2 # Gives 2 -``` - -**Mistake 2: Forgetting that mixing int and float gives float** - -```python -result: float = 5 + 2.0 # Result is 2.0, not an int -# This often surprises people because 5 is an int, but the result is float -``` - -**Mistake 3: Trying to use `/` for exponentiation** - -```python -# WRONG: This is division by 2, not 2 to the power -result: float = 5 / 2 # 2.5 (not what you want) - -# CORRECT: Use ** for exponentiation -result: int = 5 ** 2 # 25 (5 squared) -``` - ---- - -## Try With AI - -Ready to apply all 7 arithmetic operators in real calculations? - -**🔍 Explore Operator Behaviors:** -> "Compare the 7 arithmetic operators (+, -, *, /, //, %, **). For 10 and 3, show me the result of each operation and explain: (1) what type the result is (int or float?), (2) why / returns float but // returns int, (3) when I'd use each operator in real applications. Include type() verification for each result." - -**🎯 Practice Calculator Building:** -> "Create a calculator program that takes num1 = 10 and num2 = 3, performs all 7 operations, and displays results with f-strings like '10 + 3 = 13'. Add type hints for all variables. Then review my code for: correct operator usage, proper type hints (especially division results), and clear output formatting. Point out any type inconsistencies." - -**🧪 Test Division Edge Cases:** -> "I'm calculating how many groups of 3 people I can make from 10 people. Compare 10 / 3 vs. 10 // 3. Which is correct for counting groups? Show me: (1) the result and type of each, (2) why one makes sense for counting and the other doesn't, (3) what happens with 10 / 0 vs. 10 // 0. Create code demonstrating the ZeroDivisionError." - -**🚀 Apply to Your Calculations:** -> "I need to do these calculations in my project: [describe calculations like splitting items, calculating prices, computing averages, etc.]. For each, recommend which arithmetic operator(s) to use. Add validation to prevent division by zero and explain why some operations need float while others need int results." - ---- diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/02-comparison-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/02-comparison-operators.md deleted file mode 100644 index 8fea56cb9..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/02-comparison-operators.md +++ /dev/null @@ -1,227 +0,0 @@ ---- -title: "Comparison Operators — Making True/False Decisions" -chapter: 15 -lesson: 2 -duration_minutes: 50 - -# HIDDEN SKILLS METADATA (Institutional Integration Layer) -skills: - - name: "Comparison Logic with Type Awareness" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Understand + Apply" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can write comparisons like 5 > 3, x == y, predict True/False results, explain why 5 == 5.0 gives True" - - - name: "Boolean Results and Type Validation" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Understand" - digcomp_area: "Digital Content Creation" - measurable_at_this_level: "Student can verify comparisons return bool type using type(), understand True/False as values not strings" - - - name: "Preparing for Conditional Logic (Chapter 19 Foundation)" - proficiency_level: "A2" - category: "Conceptual" - bloom_level: "Understand" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can explain why comparisons precede if statements in Chapter 19 and give examples" - -learning_objectives: - - objective: "Understand what each comparison operator (==, !=, >, <, >=, <=) does" - proficiency_level: "A2" - bloom_level: "Understand" - assessment_method: "Explanation of operators; code predictions" - - - objective: "Apply comparison operators correctly to evaluate expressions and predict True/False results" - proficiency_level: "A2" - bloom_level: "Apply" - assessment_method: "Write comparisons; predict outcomes; verify with type()" - -cognitive_load: - new_concepts: 5 - assessment: "5 new concepts (equality comparison, magnitude comparison, combined comparison, boolean result type, value vs type equality) within A2 limit of 7 ✓" - -differentiation: - extension_for_advanced: "Explore type coercion in comparisons; ask AI about why True == 1 and False == 0; investigate string comparison (lexicographic ordering)" - remedial_for_struggling: "Start with simple integer comparisons (5 > 3); practice each operator in isolation before combining; use concrete numbers before variables" - -# Generation metadata -generated_by: "content-implementer v3.0.0" -source_spec: "specs/part-4-chapter-17/spec.md" -created: "2025-11-08" -last_modified: "2025-11-08" -git_author: "Claude Code" -workflow: "content-implementer subagent" -version: "1.0.0" ---- - -# Comparison Operators — Making True/False Decisions - -Now that you can do math with arithmetic operators, it's time to ask questions. Can I compare two values? Is 10 bigger than 5? Are these two numbers the same? Comparison operators let you answer these questions. Instead of doing math and getting a number back, comparisons return True or False—answers to yes/no questions. - -Think of comparison operators like a referee in a game: they look at two things, make a judgment, and give you an answer: "True" (yes, this condition is met) or "False" (no, it's not). - -## What It Is: Asking True/False Questions - -A **comparison operator** evaluates whether a condition is true or false. When you write `5 > 3`, you're asking Python: "Is 5 greater than 3?" Python answers: "True." - -Python has **six comparison operators**: - -- `==` **Equality** — Are these values the same? -- `!=` **Not equal** — Are these values different? -- `>` **Greater than** — Is the left side bigger? -- `<` **Less than** — Is the left side smaller? -- `>=` **Greater than or equal** — Is the left side bigger or the same? -- `<=` **Less than or equal** — Is the left side smaller or the same? - -All comparisons return a **boolean value**: either `True` or `False`. This is different from arithmetic operators, which return numbers. Comparisons return yes/no answers. - -## The Six Comparison Operators - -Let's see all six in action. Each one asks a different question about two values. - -### Equality and Inequality: Are They the Same? - -```python -# Equality: asking if values are the same -x: int = 10 -y: int = 5 - -equal: bool = x == y # False - 10 is not equal to 5 -print(f"{x} == {y}: {equal}") # 10 == 5: False - -# Inequality: asking if values are different -not_equal: bool = x != y # True - 10 is different from 5 -print(f"{x} != {y}: {not_equal}") # 10 != 5: True - -# Type verification - comparisons return bool -print(f"Type of result: {type(equal)}") # -``` - -Important distinction: In Lesson 1, we saw that `=` assigns a value to a variable. Here, `==` compares two values. One `=` stores; two `==` compare. This is a common mistake, so remember it well. - -#### 💬 AI Colearning Prompt - -> "Why does Python use = for assignment but == for equality checking? Compare this to other programming languages. Why is this distinction important?" - -Notice that we're asking AI to explain the **design choice** behind the operators, not just what they do. This helps you understand Python's thinking, not memorize syntax. - -### Magnitude Comparisons: Which is Bigger? - -```python -# Greater than and less than -x: int = 10 -y: int = 5 - -greater: bool = x > y # True - 10 is greater than 5 -print(f"{x} > {y}: {greater}") # 10 > 5: True - -less: bool = x < y # False - 10 is NOT less than 5 -print(f"{x} < {y}: {less}") # 10 < 5: False - -# Greater than or equal, less than or equal -greater_equal: bool = x >= y # True - 10 is greater than or equal to 5 -print(f"{x} >= {y}: {greater_equal}") # 10 >= 5: True - -less_equal: bool = x <= y # False - 10 is NOT less than or equal to 5 -print(f"{x} <= {y}: {less_equal}") # 10 <= 5: False - -# What about comparing a value with itself? -same: bool = x >= x # True - 10 is equal to 10 -print(f"{x} >= {x}: {same}") # 10 >= 10: True -``` - -The operators `>`, `<`, `>=`, `<=` compare magnitude—which value is bigger. They answer: "Is the left side bigger, smaller, or equal?" The `=` in `>=` and `<=` means "or equal to," so `10 >= 10` is True (they're equal). - -#### 🎓 Expert Insight - -> In AI-native development, you don't memorize the difference between `>` and `>=`. You think: "Do I want to include the equal case or not?" Then you use the operator that matches your intent. If you're uncertain, you ask AI: "Should I use > or >= here?" and let AI help you reason through the condition. - -### Value Equality vs. Type Equality - -Here's something that surprises many beginners: Python compares **values**, not types. - -```python -# Integer 5 and float 5.0 are VALUE-equal (but different types) -int_five: int = 5 -float_five: float = 5.0 - -# These have different types -type_different: bool = type(int_five) != type(float_five) # True - types differ -print(f"Types are different: {type_different}") # True - -# But the VALUES are equal -values_equal: bool = int_five == float_five # True - values are the same -print(f"Values are equal: {values_equal}") # True - -# String "5" is NOT equal to integer 5 -string_five: str = "5" -string_int_compare: bool = int_five == string_five # False - different types AND values - -print(f"5 == 5.0: {int_five == float_five}") # True (value equality) -print(f"5 == '5': {int_five == string_five}") # False (different types) -``` - -This is crucial: `5 == 5.0` returns True because the **values** are the same, even though one is int and one is float. But `5 == "5"` returns False because "5" is text, not a number. - -#### 🤝 Practice Exercise - -> **Ask your AI**: "I'm confused about why 5 == 5.0 is True, but 5 == '5' is False. Explain value equality vs. type equality. When does Python care about types vs. just values in comparisons?" - -**Expected Outcome**: You'll understand that `==` checks if values are the same (regardless of type in most cases), but type mismatches between completely different types (int vs. string) make them not equal. You'll see how Python's flexibility can be useful but also requires careful thinking. - -### Comparisons in Real Scenarios - -```python -# Real scenario: Checking age eligibility -user_age: int = 16 -voting_age: int = 18 -driving_age: int = 16 - -can_vote: bool = user_age >= voting_age # False (16 is not >= 18) -can_drive: bool = user_age >= driving_age # True (16 is >= 16) - -print(f"Can vote: {can_vote}") # False -print(f"Can drive: {can_drive}") # True - -# Another real scenario: Password length -password: str = "SecurePass123" -min_length: int = 8 - -is_long_enough: bool = len(password) >= min_length # True -print(f"Password meets length requirement: {is_long_enough}") - -# Checking if values are in a specific range (prepare for logical operators in Lesson 3) -test_score: int = 85 -passing_score: int = 70 -perfect_score: int = 100 - -is_passing: bool = test_score >= passing_score # True -is_perfect: bool = test_score == perfect_score # False -is_valid: bool = test_score <= perfect_score # True (score can't exceed 100) -``` - -## Why Comparisons Matter for Chapter 19 - -You might wonder: "Why are we learning comparisons separately from if statements?" The answer is that comparisons are **building blocks**. In Chapter 19, you'll learn control flow: making decisions with `if` statements. When you write `if x > 5:`, that `x > 5` is a comparison operator at work. By mastering comparisons now, Chapter 19 will feel natural—you'll already understand how to ask True/False questions. - ---- - -## Try With AI - -Ready to master comparison operators and understand why = is different from ==? - -**🔍 Explore Comparison Operators:** -> "Explain the 6 comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`. For each, show me 2 examples with numbers and explain the True/False result. Why does Python use == for comparison but = for assignment? Show me what happens if I accidentally write if x = 5: instead of if x == 5:" - -**🎯 Practice Comparison Logic:** -> "Create a movie ticket checker: movie_age_rating = 13, user_age = 12. Write comparisons to check: (1) if user can watch (user_age >= movie_age_rating), (2) if user is too young (user_age < movie_age_rating), (3) if ages are exactly equal (user_age == movie_age_rating). For each, predict True or False, then verify with code." - -**🧪 Test Type Comparison Edge Cases:** -> "Test these comparisons and explain which return True: (1) 5 == 5.0 (int vs. float), (2) '5' == 5 (string vs. int), (3) True == 1 (bool vs. int), (4) False == 0 (bool vs. int). Why does Python treat some cross-type comparisons as equal but not others? Show me the type() of each value." - -**🚀 Apply to Your Validation:** -> "I'm building [describe your application]. Help me write comparison logic for: age restrictions, price checks, quota limits, version compatibility, or other validation rules. For each condition, show me the correct comparison operator and explain why that operator is the right choice." - ---- diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/03-logical-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/03-logical-operators.md deleted file mode 100644 index 5e874d4d5..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/03-logical-operators.md +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: "Logical Operators — Combining Conditions" -chapter: 15 -lesson: 3 -duration_minutes: 50 - -# HIDDEN SKILLS METADATA (Institutional Integration Layer) -skills: - - name: "Boolean Logic with and, or, not" - proficiency_level: "A2-B1" - category: "Technical" - bloom_level: "Understand + Apply" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can write (x > 5) and (x < 10), predict True/False results, explain when each operator returns True" - - - name: "Combining Comparisons into Complex Conditions" - proficiency_level: "B1" - category: "Technical" - bloom_level: "Analyze" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can analyze expression like not (x > 5 or y < 3) and trace evaluation step-by-step with AI support" - - - name: "Truth Tables and Logical Reasoning" - proficiency_level: "A2" - category: "Conceptual" - bloom_level: "Understand" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can explain 'and returns True only if BOTH are True' and 'or returns True if AT LEAST ONE is True'" - -learning_objectives: - - objective: "Understand what logical operators (and, or, not) do and when each returns True" - proficiency_level: "A2" - bloom_level: "Understand" - assessment_method: "Explanation of operators; truth table predictions" - - - objective: "Apply logical operators to combine comparisons and create complex conditions" - proficiency_level: "A2-B1" - bloom_level: "Apply" - assessment_method: "Write combined conditions; predict outcomes; verify with code" - -cognitive_load: - new_concepts: 3 - assessment: "3 new concepts (and operator, or operator, not operator) representing fundamental boolean logic within A2-B1 limit of 7 ✓" - -differentiation: - extension_for_advanced: "Explore operator precedence (not > and > or); analyze complex nested conditions like not (a or b) and (c or d); investigate short-circuit evaluation" - remedial_for_struggling: "Start with truth tables for each operator in isolation; practice combining two simple comparisons before complex expressions; use concrete True/False values before variables" - -# Generation metadata -generated_by: "lesson-writer v3.0.0" -source_spec: "specs/part-4-chapter-17/spec.md" -created: "2025-11-08" -last_modified: "2025-11-08" -git_author: "Claude Code" -workflow: "lesson-writer subagent" -version: "1.0.0" ---- - -# Logical Operators — Combining Conditions - -You've learned to ask simple True/False questions with comparison operators. Now it's time to ask more complex questions. "Is this value between 5 and 10?" That's not one comparison—it's two comparisons combined: "Is it greater than 5 AND less than 10?" - -Logical operators let you combine True/False values (or comparisons) into more sophisticated reasoning. They're the foundation for all decision-making in Chapter 19's control flow. - -## What It Is: Combining True/False Values - -A **logical operator** combines two True/False conditions into a single True/False result. There are three logical operators: - -- `and` — True only if **both** conditions are True -- `or` — True if **at least one** condition is True -- `not` — Reverses the value (True becomes False, False becomes True) - -With these three operators, you can express complex logic: "Is the user logged in AND has been a member for 7+ days?" or "Does the password have 8+ characters OR has the user verified their email?" - -## The Three Logical Operators - -### AND: Both Conditions Must Be True - -```python -# AND operator: both must be True -condition1: bool = True -condition2: bool = False - -and_result: bool = condition1 and condition2 # False (one is False) -print(f"True and False = {and_result}") # False - -# Another example -condition3: bool = True -condition4: bool = True - -and_result2: bool = condition3 and condition4 # True (both are True) -print(f"True and True = {and_result2}") # True - -# Truth table for AND -print("AND Truth Table:") -print(f"True and True = {True and True}") # True -print(f"True and False = {True and False}") # False -print(f"False and True = {False and True}") # False -print(f"False and False = {False and False}") # False -``` - -The `and` operator has a simple rule: it returns True **only if both conditions are True**. If even one is False, the whole expression is False. This is useful for checking multiple requirements. - -#### 💬 AI Colearning Prompt - -> "Why does Python short-circuit evaluation with `and`? In other words, if the first condition is False, why does Python stop checking the second condition? What's the advantage?" - -This question digs into how Python optimizes logical evaluation—a valuable understanding for later performance considerations. - -### OR: At Least One Condition Must Be True - -```python -# OR operator: at least one must be True -condition1: bool = True -condition2: bool = False - -or_result: bool = condition1 or condition2 # True (one is True) -print(f"True or False = {or_result}") # True - -# Another example -condition3: bool = False -condition4: bool = False - -or_result2: bool = condition3 or condition4 # False (both are False) -print(f"False or False = {or_result2}") # False - -# Truth table for OR -print("OR Truth Table:") -print(f"True or True = {True or True}") # True -print(f"True or False = {True or False}") # True -print(f"False or True = {False or True}") # True -print(f"False or False = {False or False}") # False -``` - -The `or` operator returns True if **at least one condition is True**. It's False only when both are False. Use `or` when you want to check if any of multiple conditions is satisfied. - -#### 🎓 Expert Insight - -> In AI-native development, you don't memorize truth tables. You think about the real-world logic: "AND means both must be satisfied; OR means either one is enough." Once you have that mental model, the logic follows naturally. If you get confused, ask AI: "Should I use and or or here?" and explain your logic. - -### NOT: Reversing a Value - -```python -# NOT operator: flips the value -condition: bool = True -not_result: bool = not condition # False (True becomes False) -print(f"not True = {not_result}") # False - -condition2: bool = False -not_result2: bool = not condition2 # True (False becomes True) -print(f"not False = {not_result2}") # True - -# Combining NOT with other operators -is_admin: bool = False -is_not_admin: bool = not is_admin # True -print(f"Is not admin: {is_not_admin}") # True -``` - -The `not` operator is the simplest: it just flips the value. If the condition is True, `not condition` is False. If it's False, `not condition` is True. - -#### 🤝 Practice Exercise - -> **Ask your AI**: "Create a truth table showing all combinations of `and`, `or`, and `not` operators. Then explain: What's the relationship between `not (x and y)` and `(not x) or (not y)`? Why does this matter?" - -**Expected Outcome**: You'll see that logical operators follow mathematical laws (De Morgan's Laws); understand that different expressions can be logically equivalent; see how logic works systematically, not randomly. - -## Combining Comparisons with Logical Operators - -Now let's combine what you learned in Lesson 2 (comparisons) with logical operators. - -### Checking if a Value is in a Range - -```python -# Is x between 5 and 10? -x: int = 7 - -in_range: bool = (x > 5) and (x < 10) # True (both conditions are met) -print(f"Is {x} between 5 and 10? {in_range}") # True - -# Note: We use parentheses for clarity (not required, but helpful) - -# Is x OUTSIDE the range [5, 10]? -out_of_range: bool = (x <= 5) or (x >= 10) # False (neither condition is met) -print(f"Is {x} outside [5, 10]? {out_of_range}") # False - -# Is x NOT in the range? -not_in_range: bool = not ((x > 5) and (x < 10)) # False (it IS in range) -print(f"Is {x} NOT in range? {not_in_range}") # False -``` - -These are the kinds of conditions you'll use constantly in Chapter 19 when writing `if` statements. - -### Real-World Permission Logic - -```python -# Permission check: User can post if logged in AND account is verified -is_logged_in: bool = True -account_verified: bool = False - -can_post: bool = is_logged_in and account_verified # False (verification missing) -print(f"Can post: {can_post}") # False - -# Alternative permission: Admin OR approved user -is_admin: bool = False -is_approved_user: bool = True - -can_manage: bool = is_admin or is_approved_user # True (approved user is enough) -print(f"Can manage content: {can_manage}") # True - -# Complex condition: (Admin OR Moderator) AND Account Active -is_moderator: bool = True -account_active: bool = True - -can_moderate: bool = (is_admin or is_moderator) and account_active # True -print(f"Can moderate: {can_moderate}") # True -``` - -Notice how parentheses control the order of evaluation. `(is_admin or is_moderator) and account_active` evaluates the OR part first, then checks if the account is active. - -## Evaluation Order Matters - -When you combine multiple logical operators, Python evaluates them in a specific order: `not` first, then `and`, then `or`. - -```python -# Without explicit parentheses, Python follows operator precedence -result: bool = True or False and False # What's the result? -# Python evaluates: (True or (False and False)) -# False and False = False -# True or False = True -print(f"True or False and False = {result}") # True - -# With explicit parentheses, we control the order -result2: bool = (True or False) and False # Different result -# (True or False) = True -# True and False = False -print(f"(True or False) and False = {result2}") # False -``` - -This is why using parentheses is smart—even when not required, they make your intent clear to anyone reading your code (including yourself three months from now). - ---- - -## Try With AI - -Ready to combine conditions with and, or, and not operators? - -**🔍 Explore Logical Operator Behavior:** -> "Explain and, or, and not operators with truth tables. For each operator, show me 3 examples combining boolean values and explain the result. Why does 'True and False' return False but 'True or False' returns True? Include short-circuit evaluation: does 'False and expensive_function()' call the function?" - -**🎯 Practice Access Control Logic:** -> "Create access control for premium content. Users can access if: (is_subscriber AND is_active) OR is_admin. Test these 3 cases: (1) subscriber=True, active=True, admin=False, (2) subscriber=False, active=False, admin=True, (3) subscriber=True, active=False, admin=False. Show the step-by-step evaluation. Then compare to this modified rule: (is_subscriber OR is_admin) AND is_active. How do results change?" - -**🧪 Test Operator Precedence:** -> "Compare these two rules for an admin with inactive account (subscriber=False, active=False, admin=True): Rule A: is_subscriber AND is_active OR is_admin, Rule B: (is_subscriber OR is_admin) AND is_active. Which grants access and which denies? Show me how parentheses change the evaluation order. Which rule is more secure for access control?" - -**🚀 Apply to Your Business Logic:** -> "I'm building [describe your system]. Help me write multi-condition logic for: user permissions, eligibility checks, validation rules, or workflow conditions. For each rule, combine conditions with and, or, not. Add parentheses to make precedence clear. Explain why each condition is necessary." - ---- diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/04-assignment-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/04-assignment-operators.md deleted file mode 100644 index df3b65e71..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/04-assignment-operators.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: "Assignment Operators — Updating Variables Efficiently" -chapter: 15 -lesson: 4 -duration_minutes: 50 - -# HIDDEN SKILLS METADATA (Institutional Integration Layer) -skills: - - name: "Basic and Shorthand Assignment" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Understand + Apply" - digcomp_area: "Digital Content Creation" - measurable_at_this_level: "Student can write x += 5 equivalent to x = x + 5; apply shorthand operators without reference; understand equivalence" - - - name: "Understanding Assignment vs. Comparison" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Understand" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can distinguish = (assignment) from == (comparison); explain why confusing them causes SyntaxError" - - - name: "Practical Variable Updates in Code" - proficiency_level: "A2" - category: "Technical" - bloom_level: "Apply" - digcomp_area: "Digital Content Creation" - measurable_at_this_level: "Student can use count += 1 in realistic scenarios; recognize when shorthand is more readable than expanded form" - -learning_objectives: - - objective: "Understand what assignment operators (=, +=, -=, *=, /=) do" - proficiency_level: "A2" - bloom_level: "Understand" - assessment_method: "Explanation of shorthand vs. expanded form; equivalence verification" - - - objective: "Apply assignment operators to update variables efficiently" - proficiency_level: "A2" - bloom_level: "Apply" - assessment_method: "Write shorthand operators; predict outcomes; use in realistic patterns" - -cognitive_load: - new_concepts: 5 - assessment: "5 new concepts (basic assignment, += operator, -= operator, *= operator, /= operator) within A2 limit of 7 ✓" - -differentiation: - extension_for_advanced: "Explore other assignment operators (%=, //=, **=); investigate when shorthand vs. expanded form is clearer; ask AI about performance implications" - remedial_for_struggling: "Start with += operator only; practice equivalence (x += 3 means x = x + 3); build confidence before introducing other operators" - -# Generation metadata -generated_by: "content-implementer v3.0.0" -source_spec: "specs/part-4-chapter-17/spec.md" -created: "2025-11-08" -last_modified: "2025-11-08" -git_author: "Claude Code" -workflow: "content-implementer subagent" -version: "1.0.0" ---- - -# Assignment Operators — Updating Variables Efficiently - -When you're working with variables, you often need to update them. Add 5 to a counter. Subtract a cost from a total. Multiply a score by a multiplier. You could write `count = count + 5`, but Python gives you a shorter way: `count += 5`. These are **assignment operators**—they combine an arithmetic operation with assignment in one expression. - -Think of assignment operators as shortcuts. Instead of writing the long form, you write the short form. They do the same thing, just more concisely. - -## What It Is: Shorthand for Updating Variables - -An **assignment operator** updates a variable by combining an operation with assignment. The most common are: - -- `=` **Basic assignment** — store a value (we've been using this) -- `+=` **Add and assign** — add to the current value -- `-=` **Subtract and assign** — subtract from the current value -- `*=` **Multiply and assign** — multiply the current value -- `/=` **Divide and assign** — divide the current value - -All of these make code more readable and concise. - -## Assignment vs. Comparison: Critical Distinction - -Before we go further, let's reinforce something from Lesson 2. There are three different "equals" symbols in Python, and they mean different things: - -- `=` **Assignment** — store a value in a variable -- `==` **Comparison** — ask if two values are equal -- `+=` **Assignment with operation** — add and store - -Using the wrong one is a common mistake. Here's why it matters: - -```python -# CORRECT: x = 5 (assignment) -x: int = 5 -print(x) # 5 - -# INCORRECT: if x = 5: (syntax error in if statement) -# This fails because if expects a True/False condition, not an assignment - -# CORRECT: if x == 5: (comparison) -if x == 5: - print("x is 5") # This works! - -# CORRECT: x += 5 (assignment with addition) -x += 5 -print(x) # 10 -``` - -Assignment operators start with a symbol from Lesson 1 (arithmetic), then end with `=`. So `+=` means "add and assign," `*=` means "multiply and assign," etc. - -#### 💬 AI Colearning Prompt - -> "Why does Python use three different 'equals' operators (=, ==, +=)? Why not use something like `add x 5` or `add-assign x 5` instead? Explain the design reasoning." - -This helps you understand Python's philosophy about clarity and consistency in syntax. - -## The Five Assignment Operators - -Let's see each assignment operator with equivalent expanded forms. - -### Addition and Subtraction Assignment - -```python -# Addition assignment: += -count: int = 10 - -# Method 1: Expanded form (long way) -count: int = count + 5 -print(f"After + : {count}") # 15 - -# Method 2: Shorthand (equivalent, cleaner) -count: int = 10 -count += 5 -print(f"After +=: {count}") # 15 (same result) - -# These two are equivalent: -# count = count + 5 -# count += 5 - -# Subtraction assignment: -= -balance: float = 100.0 - -balance -= 25.0 # Subtract and assign -print(f"Balance after withdrawal: {balance}") # 75.0 - -# Equivalent to: balance = balance - 25.0 -``` - -The `+=` operator adds a value to the current value and stores the result back. `count += 5` means "take the current value of count, add 5, and store the result back in count." Same for `-=`, just with subtraction. - -#### 🎓 Expert Insight - -> In AI-native development, you don't worry about memorizing the difference between `count = count + 5` and `count += 5`. You use whichever feels more readable in context. Most Python developers prefer `+=` because it's concise and shows your intent clearly: "increment this variable." If you forget the syntax, ask AI: "Show me the shorthand for adding 5 to count," and move on. - -### Multiplication and Division Assignment - -```python -# Multiplication assignment: *= -price: float = 100.0 - -# Apply a 10% price increase -price *= 1.10 # Multiply and assign -print(f"New price: ${price:.2f}") # $110.00 - -# Equivalent to: price = price * 1.10 - -# Division assignment: /= -total: float = 100.0 - -# Split cost equally among 4 people -total /= 4 -print(f"Cost per person: ${total:.2f}") # $25.00 - -# Equivalent to: total = total / 4 -# Note: This returns a float, even if total was an int! -``` - -The `*=` operator is very useful for percentages and scaling. The `/=` operator is useful for averaging or dividing quantities. Remember: `/=` always produces a float result (same as `/` from Lesson 1). - -#### 🤝 Practice Exercise - -> **Ask your AI**: "Write code that tracks a bank account: -> 1. Start with balance = 1000 -> 2. Add a deposit: balance += 500 -> 3. Subtract a withdrawal: balance -= 200 -> 4. Apply interest (multiply by 1.05): balance *= 1.05 -> 5. Show the final balance and its type -> -> Explain what happens to the type when you use /= on an integer variable." - -**Expected Outcome**: You'll see assignment operators used in realistic financial scenarios; understand type behavior (int to float when using /=); practice reading and predicting code behavior. - -## Assignment Operators in Common Patterns - -### The Counter Pattern - -The most common use of `+=` is counting: - -```python -# Pattern: Starting a counter at 0, incrementing it -count: int = 0 - -# Simulate processing items -items: list[str] = ["apple", "banana", "cherry", "date"] - -for item in items: - count += 1 # Increment by 1 - print(f"Item {count}: {item}") - -print(f"Total items: {count}") # 4 -``` - -You'll see `count += 1` everywhere in Chapter 19 (loops). This pattern is so common it's almost universal. - -### The Accumulator Pattern - -Another common pattern is accumulating a total: - -```python -# Pattern: Starting a total at 0, adding values to it -total: float = 0.0 - -# Simulate processing prices -prices: list[float] = [10.50, 20.99, 15.00] - -for price in prices: - total += price # Add to the running total - print(f"Running total: ${total:.2f}") - -print(f"Final total: ${total:.2f}") # $46.49 -``` - -Again, you'll see this pattern frequently in Chapter 19. - -## Type Behavior with Assignment Operators - -Remember from Lesson 1 that types can change during operations. Assignment operators follow the same rules: - -```python -# Integer arithmetic with += -value: int = 5 -value += 2 # Still int -print(f"value = {value}, type = {type(value)}") # 7, - -# But division assignment changes to float -value: int = 10 -value /= 2 # Changes to float! -print(f"value = {value}, type = {type(value)}") # 5.0, - -# Mixing types in assignment -mixed: int = 5 -mixed += 2.5 # int + float = float -print(f"mixed = {mixed}, type = {type(mixed)}") # 7.5, - -# String concatenation (string + is supported) -greeting: str = "Hello" -greeting += " World" # String concatenation -print(greeting) # "Hello World" -``` - -Type behavior with assignment operators follows the same rules as regular operators from Lesson 1. This consistency makes it predictable. - ---- - -## Try With AI - -Ready to update variables efficiently with assignment operators? - -**🔍 Explore Assignment Operator Mechanics:** -> "Compare regular assignment with compound operators. Show me: (1) score = score + 10 vs. score += 10—are they equivalent? (2) For +=, -=, *=, /=, //= show examples with type() checks. (3) Why does /= change int to float but //= keeps int? (4) Demonstrate that score += 5 is shorter AND faster than score = score + 5." - -**🎯 Practice Score Tracking:** -> "Create a game score tracker starting at 0. Apply these events: collect 10 coins (+=), lose 3 coins (-=), double score (power-up using *=), split between 2 players (/=), round down (//=). After each operation, show: current score, type() result, and explain why the type changes or stays the same. Predict the final score before running code." - -**🧪 Test Operators with Different Types:** -> "Show me assignment operators with strings: (1) Build 'Hello World!' character-by-character using += starting from empty string. (2) Use *= to repeat 'Hi' 3 times. (3) Explain why += works for both numbers and strings but -= doesn't work for strings. (4) Try score -= 'text' and show me the TypeError that occurs." - -**🚀 Apply to Your State Management:** -> "I'm building [describe your application]. Help me track changing values like: account balances (deposits/withdrawals with += and -=), counters (page views with +=), multipliers (discounts with *=), or accumulated totals. For each case, show the appropriate assignment operator and explain why it's the right choice. Add type hints and validation." - ---- diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/05-keywords-capstone.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/05-keywords-capstone.md deleted file mode 100644 index 8c4ef3992..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/05-keywords-capstone.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: "Keywords and Capstone: Building a Type-Safe Calculator" -chapter: 15 -lesson: 5 -duration_minutes: 50 - -# HIDDEN SKILLS METADATA (Institutional Integration Layer) -skills: - - name: "Recognizing Python Keywords" - proficiency_level: "A1-A2" - category: "Technical" - bloom_level: "Remember + Understand" - digcomp_area: "Foundation" - measurable_at_this_level: "Student can retrieve keyword list with import keyword, recognize common keywords (if,for,while,def,class,return), avoid using as variable names" - - - name: "Understanding Why Keywords are Reserved" - proficiency_level: "A2" - category: "Conceptual" - bloom_level: "Understand" - digcomp_area: "Problem-Solving" - measurable_at_this_level: "Student can explain 'Keywords are reserved because Python needs them for control flow, functions, and language features' with examples" - - - name: "Integrating All Operator Types in Realistic Code" - proficiency_level: "A2-B1" - category: "Technical" - bloom_level: "Apply + Analyze" - digcomp_area: "Digital Content Creation" - measurable_at_this_level: "Student can write Calculator project using all 4 operator types, validate output with type()" - - - name: "Validation-First Programming Practice" - proficiency_level: "A2-B1" - category: "Technical" - bloom_level: "Apply" - digcomp_area: "Safety" - measurable_at_this_level: "Student tests code with multiple inputs, validates types, checks edge cases, asks AI about surprising results" - -learning_objectives: - - objective: "Recognize and list Python keywords and understand why they're reserved" - proficiency_level: "A1-A2" - bloom_level: "Remember + Understand" - assessment_method: "Keyword list retrieval; explanation of why reserved" - - - objective: "Apply all four operator types in an integrated capstone project" - proficiency_level: "A2-B1" - bloom_level: "Apply + Analyze" - assessment_method: "Calculator project completion; type validation; testing" - -cognitive_load: - new_concepts: 2 - assessment: "2 new concepts (keywords, keyword checking) plus integration of 4 operator types (no new operator concepts) within A2-B1 limit of 10 ✓" - -differentiation: - extension_for_advanced: "Add more calculator operations (%, //); implement error handling for invalid input; create a menu-driven calculator with multiple operation choices" - remedial_for_struggling: "Use simplified calculator without functions; focus on one operator type at a time; add explanation comments for each section" - -# Generation metadata -generated_by: "lesson-writer v3.0.0" -source_spec: "specs/part-4-chapter-17/spec.md" -created: "2025-11-08" -last_modified: "2025-11-08" -git_author: "Claude Code" -workflow: "lesson-writer subagent" -version: "1.0.0" ---- - -# Keywords and Capstone: Building a Type-Safe Calculator - -You've mastered four types of operators. Now it's time to learn one more important concept about Python's language structure: **keywords**. Keywords are reserved words that Python has claimed for itself. You can't use them as variable names because Python needs them for language features. - -Then we'll bring everything together in a capstone project: a calculator that demonstrates all four operator types, combined with keyword awareness and type validation. - -## What It Is: Python's Reserved Words - -A **keyword** is a word that Python uses for language syntax. These words have special meaning and control how Python works. Because Python needs them for specific purposes, you can't use them as variable names. - -Python has **35 keywords** (as of Python 3.14). You don't need to memorize them—you need to recognize common ones and know how to check if a word is reserved. - -### Discovering Python Keywords - -Python provides a simple way to see all keywords: - -```python -# Import the keyword module -import keyword - -# See all Python keywords -print("Python keywords:") -print(keyword.kwlist) - -# Output (abbreviated): -# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', -# 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', -# 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', -# 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', -# 'while', 'with', 'yield'] - -# Count them -print(f"Total keywords: {len(keyword.kwlist)}") # 35 - -# Check if a specific word is a keyword -print(keyword.iskeyword("for")) # True (reserved) -print(keyword.iskeyword("forloop")) # False (not reserved) -print(keyword.iskeyword("count")) # False (not reserved) -``` - -These 35 keywords are Python's grammar. They define language structure: loops (`for`, `while`), conditionals (`if`, `else`), functions (`def`), classes (`class`), and more. - -#### 💬 AI Colearning Prompt - -> "Why can't I use keywords as variable names? What would happen to Python's design if `if`, `for`, or `def` weren't reserved? Explain the problem and why reservation is necessary." - -This question helps you understand language design—why certain words must be protected. - -### Why Keywords Are Reserved - -Let's see what happens when you try to use a keyword as a variable name: - -```python -# WRONG: Trying to use 'for' as a variable -# for = 5 # SyntaxError: invalid syntax (for is reserved!) - -# RIGHT: Use a descriptive alternative -for_loop_count: int = 5 # Underscore makes it clear -loop_count: int = 5 # Descriptive name -iterations: int = 5 # Alternative name - -# Common keywords and what they do -# if, elif, else — conditional logic (Chapter 19) -# for, while — loops (Chapter 19) -# def — define functions (Chapter 22) -# class — define classes (Chapter 26) -# import, from — import modules (Chapter 22) -# return — return from function (Chapter 22) -# try, except, finally — error handling (Chapter 23) -# True, False, None — special values (Chapter 16) -# and, or, not — logical operators (Lesson 3, this chapter!) -``` - -The reason `for`, `if`, `def` are reserved is that Python needs them for language structure. If you could write `for = 5`, Python would get confused: "Is this the start of a for loop, or is this assigning 5 to the variable for?" - -#### 🎓 Expert Insight - -> In AI-native development, you don't memorize all 35 keywords. You develop a reflex: "If I get a SyntaxError when naming a variable, it might be a keyword. Let me check with `keyword.iskeyword()`." This defensive habit will save you debugging time. - -### Checking if a Word is Reserved - -A smart programming practice is to check before using a word as a variable name: - -```python -import keyword - -# Function to check if a name is valid (simplified) -def is_valid_name(word: str) -> bool: - """Check if a word is not a keyword""" - return not keyword.iskeyword(word) - -# Test it -potential_names: list[str] = ["count", "for", "result", "while", "data"] - -for name in potential_names: - if keyword.iskeyword(name): - print(f" '{name}' is RESERVED - use '{name}_var' instead") - else: - print(f" '{name}' is OK - can use as variable name") - -# Output: -# count is OK -# for is RESERVED - use for_var instead -# result is OK -# while is RESERVED - use while_var instead -# data is OK -``` - -This pattern—checking before using—is good defensive programming. - -#### 🤝 Practice Exercise - -> **Ask your AI**: "Create a program that: -> 1. Lists all 35 Python keywords -> 2. Groups them by category (control flow, function definition, special values, etc.) -> 3. Explains what each category does -> -> Then explain: Why do you think keywords are organized this way? What would happen if Python had no keywords?" - -**Expected Outcome**: You'll see that keywords follow logical categories; understand that language design requires structure; appreciate why Python protects certain words. - -## Capstone Project: Calculator with Type Safety - -Now let's bring everything together. You'll create a calculator that demonstrates: -- **Arithmetic operators** (Lesson 1): `+`, `-`, `*`, `/`, `//`, `%` -- **Comparison operators** (Lesson 2): `==`, `!=`, `>`, `<`, `>=`, `<=` -- **Logical operators** (Lesson 3): `and`, `or`, `not` -- **Assignment operators** (Lesson 4): `=`, `+=`, `-=`, `*=`, `/=` -- **Type validation**: Using `type()` to verify results -- **Keyword awareness**: Recognizing reserved words - -### Simplified Calculator (Beginner-Friendly Version) - -If you haven't learned functions yet, here's a straightforward version: - -```python -# DEMO: Interactive calculator (requires user input) -# Capstone Project: Simple Calculator with Type Safety -# Demonstrates all 4 operator types + type validation + keyword awareness - -import keyword - -print("=" * 50) -print("SIMPLE CALCULATOR WITH TYPE SAFETY") -print("=" * 50) - -# Input two numbers -num1: float = float(input("\nEnter first number: ")) -num2: float = float(input("Enter second number: ")) - -# Arithmetic operators (Lesson 1) -print("\n--- ARITHMETIC OPERATORS ---") -add_result: float = num1 + num2 -print(f"{num1} + {num2} = {add_result} (type: {type(add_result).__name__})") - -sub_result: float = num1 - num2 -print(f"{num1} - {num2} = {sub_result} (type: {type(sub_result).__name__})") - -mul_result: float = num1 * num2 -print(f"{num1} * {num2} = {mul_result} (type: {type(mul_result).__name__})") - -# Comparison operators (Lesson 2) -print("\n--- COMPARISON OPERATORS ---") -is_equal: bool = num1 == num2 -print(f"{num1} == {num2}: {is_equal} (type: {type(is_equal).__name__})") - -is_greater: bool = num1 > num2 -print(f"{num1} > {num2}: {is_greater} (type: {type(is_greater).__name__})") - -is_less: bool = num1 < num2 -print(f"{num1} < {num2}: {is_less} (type: {type(is_less).__name__})") - -# Logical operators (Lesson 3) -print("\n--- LOGICAL OPERATORS ---") -both_positive: bool = (num1 > 0) and (num2 > 0) -print(f"Both positive: {both_positive} (type: {type(both_positive).__name__})") - -either_large: bool = (num1 > 10) or (num2 > 10) -print(f"Either > 10: {either_large} (type: {type(either_large).__name__})") - -not_equal_result: bool = not (num1 == num2) -print(f"Not equal: {not_equal_result} (type: {type(not_equal_result).__name__})") - -# Assignment operators (Lesson 4) -print("\n--- ASSIGNMENT OPERATORS ---") -total: float = 0.0 -total += add_result -print(f"After adding result: total = {total}") - -total -= 5.0 -print(f"After subtracting 5: total = {total}") - -total *= 0.5 -print(f"After halving: total = {total} (type: {type(total).__name__})") - -# Keyword awareness -print("\n--- KEYWORD AWARENESS ---") -test_words: list[str] = ["count", "for", "result", "if", "my_var"] -print("Checking variable names:") -for word in test_words: - if keyword.iskeyword(word): - print(f" '{word}' is RESERVED - don't use as variable name") - else: - print(f" '{word}' is OK - can use as variable name") - -# Division with safety check -print("\n--- SAFE DIVISION ---") -if num2 != 0: - div_result: float = num1 / num2 - print(f"{num1} / {num2} = {div_result} (type: {type(div_result).__name__})") -else: - print("Cannot divide by zero") - -print("\n" + "=" * 50) -print("Calculation complete!") -print("=" * 50) -``` - -**Output:** -``` -================================================== -SIMPLE CALCULATOR WITH TYPE SAFETY -================================================== - ---- ARITHMETIC OPERATORS --- -10.0 + 3.0 = 13.0 (type: float) -10.0 - 3.0 = 7.0 (type: float) -10.0 * 3.0 = 30.0 (type: float) - ---- COMPARISON OPERATORS --- -10.0 == 3.0: False (type: bool) -10.0 > 3.0: True (type: bool) -10.0 < 3.0: False (type: bool) - ---- LOGICAL OPERATORS --- -Both positive: True (type: bool) -Either > 10: False (type: bool) -Not equal: True (type: bool) - ---- ASSIGNMENT OPERATORS --- -After adding result: total = 13.0 -After subtracting 5: total = 8.0 -After halving: total = 4.0 (type: float) - ---- KEYWORD AWARENESS --- -Checking variable names: - 'count' is OK - can use as variable name - 'for' is RESERVED - don't use as variable name - 'result' is OK - can use as variable name - 'if' is RESERVED - don't use as variable name - 'my_var' is OK - can use as variable name - ---- SAFE DIVISION --- -10.0 / 3.0 = 3.3333333333333335 (type: float) - -================================================== -Calculation complete! -================================================== -``` - -**That's the complete calculator!** You've now integrated all four operator types (arithmetic, comparison, logical, assignment) plus keyword awareness and type validation—all using only the Python concepts you've learned so far (Chapters 15-15). - -**What about functions?** You might wonder why the calculator code is all in one block instead of organized into functions. That's intentional! Functions are taught in Chapter 22. For now, focus on understanding how operators work together. When you reach Chapter 22, you can come back and refactor this calculator using functions as practice. - ---- - -## Try With AI - -Ready to integrate all 4 operator types into one comprehensive calculator? - -**🔍 Explore Multi-Operator Integration:** -> "Show me how arithmetic, comparison, logical, and assignment operators work together. Create a calculator that: (1) performs 7 arithmetic ops (+,-,*,/,//,%,**) on two numbers, (2) uses comparisons to validate result > 0 and < 1000, (3) uses logical operators to check (num1 > 0) and (num2 > 0), (4) uses += to track running total. Explain how each operator type serves a different purpose." - -**🎯 Practice Comprehensive Validation:** -> "Build a production-ready calculator with type hints and validation: (1) Check num2 != 0 before division operations, (2) Validate inputs are positive using logical operators, (3) Compare results against expected ranges, (4) Use assignment operators to accumulate totals, (5) Check if proposed variable names avoid Python keywords using keyword.iskeyword(). Show complete code with clear error messages." - -**🧪 Test Edge Cases:** -> "Test this calculator with 4 cases: (1) normal (10, 3), (2) zero divisor (10, 0), (3) negative inputs (-5, -3), (4) large numbers (1000000, 500000). For each test, show: arithmetic results, comparison validations, logical checks, and accumulated total. What breaks? How do we handle division by zero gracefully? Should we allow negative numbers or reject them?" - -**🚀 Apply to Your Domain Calculator:** -> "I need a calculator for [describe your domain: financial calculations, game scoring, data analysis, etc.]. Help me integrate all operator types: (1) domain-specific arithmetic operations, (2) validation ranges using comparisons, (3) multi-condition checks using logical operators, (4) state tracking with assignment operators, (5) keyword validation for user-defined names. Make it robust against bad input." - ---- - ---- - -## Chapter 17 Complete - -Congratulations! You've mastered all four operator types: arithmetic, comparison, logical, and assignment. You understand how to combine them, validate types, and recognize Python's language boundaries (keywords). - -**What's Next (Chapter 18)**: Strings and text manipulation—you'll see that operators work with strings too (concatenation with `+`, repetition with `*`). - -**Looking Ahead (Chapter 19)**: Control flow and loops—you'll use comparison and logical operators in `if` statements and loops, applying everything you learned here to make decisions and repeat code. - -Your foundation is solid. Keep this chapter's concepts close as you move forward. diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/README.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/README.md deleted file mode 100644 index 0a518b7ef..000000000 --- a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_position: 16 -title: "Chapter 16: Operators, Keywords, and Variables" ---- - -# Chapter 16: Operators, Keywords, and Variables - -In Chapter 16, you learned about Python's core data types and how to store data in variables with type hints. Now it's time to learn **what you can DO with that data** using operators—the symbols that tell Python to perform actions. - -Operators are the verbs of programming. In Chapter 16, you learned the nouns (data types). Now you learn the verbs (operators). In Chapter 19, you'll combine them into sentences (control flow). - -## What You'll Learn - -By the end of this chapter, you will: - -- Perform calculations with arithmetic operators (`+`, `-`, `*`, `/`, `//`, `%`, `**`) -- Ask True/False questions with comparison operators (`==`, `!=`, `>`, `<`, `>=`, `<=`) -- Combine conditions with logical operators (`and`, `or`, `not`) -- Update variables with assignment operators (`=`, `+=`, `-=`, `*=`, `/=`) -- Recognize Python's 35 reserved keywords and avoid using them as variable names -- Build a complete calculator integrating all operator types with type validation - -Operators are the verbs of programming. In Chapter 16, you learned the nouns (data types). Now you learn the verbs (operators). In Chapter 19, you'll combine them into sentences (control flow). diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/01-arithmetic-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/01-arithmetic-operators.md new file mode 100644 index 000000000..cc8d90114 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/01-arithmetic-operators.md @@ -0,0 +1,291 @@ +--- +title: "Arithmetic Operators" +sidebar_position: 1 +--- + +# Arithmetic Operators + +## What You'll Learn + +- Seven Arithmetic Operators +- Division vs Floor Division +- Modulus (Remainders) +- Exponentiation (Powers) +- Operator Precedence + +## The Problem + +You're building a game. Players collect coins, defeat enemies, and earn bonuses. You need to calculate scores: 10 coins worth 5 points each, a bonus multiplier of 2x, and split points among team members. How do you tell Python to do this math? + +## Why You Need Arithmetic Operators + +Arithmetic operators are symbols that tell Python to perform calculations. Without them, your game couldn't: + +- Calculate total points from coins collected +- Apply bonus multipliers to scores +- Split rewards among team members +- Compute power-ups and level bonuses + +Let's discover how Python does the math for your game. + +## Calculating Team Scores + +Let's start by discovering how Python does math. + +Player 1 scored 50 points, Player 2 scored 30. What's the team's combined score? + +```python +# Your prediction: What symbol adds numbers in Python? +player1 = 50 +player2 = 30 +team_score = player1 + player2 +print(team_score) +``` + +**Run it.** You get `80`. The `+` symbol works exactly like math class. + +Now try the others: + +```python +# Experiment: Try each operator +a = 20 +b = 6 + +print(a + b) # Addition - what do you get? +print(a - b) # Subtraction +print(a * b) # Multiplication +print(a / b) # Division +``` + +**What did you discover?** +- `+` adds (26) +- `-` subtracts (14) +- `*` multiplies (120) +- `/` divides (3.333...) + +These four work like math class. But Python has three more operators you might not know. + +## The Three Special Operators + +### Floor Division: Distributing Power-Ups Equally + +You have 20 power-ups to distribute equally among 6 players. How many does each player get? + +```python +power_ups = 20 +players = 6 + +# Try regular division first +print(power_ups / players) # What do you get? +``` + +You get `3.333...` but you can't give 3.33 power-ups. You need whole numbers only. + +```python +# Now try floor division +print(power_ups // players) # What do you get? +``` + +You get `3`. The `//` operator divides and drops the decimal—each player gets 3 power-ups. + +**Pattern discovered**: `/` gives decimal results, `//` gives whole number results. + +### Modulus: What's Left in the Pool? + +After giving 3 power-ups to each of 6 players, how many are left over? + +```python +power_ups = 20 +players = 6 + +# The modulus operator finds remainders +leftover = power_ups % players +print(leftover) # What do you get? +``` + +You get `2`. The `%` operator gives the remainder—2 power-ups left in the pool. + +**Try it yourself**: What's `17 % 5`? Predict first, then run it. + +Common uses for modulus: +- Check if even: `number % 2` gives 0 if even +- Get last digit: `number % 10` gives the ones place +- Cycle through values: `count % 3` cycles 0, 1, 2, 0, 1, 2... + +### Exponentiation: Combo Multipliers + +Your game has a combo system. Each consecutive hit doubles the bonus. After 8 consecutive hits, what's the multiplier? (2×2×2×2×2×2×2×2) + +```python +# Exponentiation uses ** +combo_multiplier = 2 ** 8 +print(combo_multiplier) # What do you get? +``` + +You get `256`. The `**` operator raises numbers to powers—that's a 256x combo bonus! + +```python +# More examples +print(3 ** 2) # 9 (3 squared) +print(10 ** 3) # 1000 (10 cubed) +print(5 ** 0) # 1 (anything to the 0 is 1) +``` + +**Warning**: Don't use `^` for powers—it does something else in Python. Always use `**`. + +## Reference Table: All Seven Operators + +| Operator | Name | Example | Result | Use When... | +|----------|------|---------|--------|-------------| +| `+` | Addition | `10 + 3` | `13` | Combining values | +| `-` | Subtraction | `10 - 3` | `7` | Finding differences | +| `*` | Multiplication | `10 * 3` | `30` | Scaling values | +| `/` | Division | `10 / 3` | `3.333...` | Need decimal precision | +| `//` | Floor Division | `10 // 3` | `3` | Need whole groups | +| `%` | Modulus | `10 % 3` | `1` | Need remainders | +| `**` | Exponentiation | `10 ** 3` | `1000` | Need powers | + +## Order of Operations + +What does `2 + 3 * 4` equal? + +```python +# Predict the result before running +result = 2 + 3 * 4 +print(result) +``` + +Did you get `14` or `20`? + +If you got `14`, you're right. Python follows math rules: multiplication before addition. + +```python +# Python evaluates: 3 * 4 = 12, then 2 + 12 = 14 +print(2 + 3 * 4) # 14 + +# Use parentheses to change the order +print((2 + 3) * 4) # 20 +``` + +**The pattern**: PEMDAS applies—Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. + +**Best practice**: Use parentheses to make your intent clear, even when not required. + +```python +# Confusing without parentheses +total = 100 * 1.08 + 5 + +# Clear with parentheses +total = (100 * 1.08) + 5 # Tax first, then add fee +``` + +## Practice: Solve Real Problems + +### Challenge 1: Score Calculator + +Calculate total score from different point sources: + +```python +# Points from different sources +coins = 10 +coin_value = 5 +enemies = 3 +enemy_value = 20 + +# Calculate totals +coin_points = coins * coin_value +enemy_points = enemies * enemy_value +total_score = coin_points + enemy_points + +print(f"Coin points: {coin_points}") +print(f"Enemy points: {enemy_points}") +print(f"Total score: {total_score}") +``` + +**Extend it**: Add bonus points of 50. What's the new total? + +### Challenge 2: Loot Distribution + +You have 23 gold coins to split among 5 party members. + +```python +gold = 23 +members = 5 + +# How much does each member get? +per_member = gold // members +print(f"Each member gets {per_member} gold") + +# How much is left for the guild bank? +guild_bank = gold % members +print(f"Guild bank gets: {guild_bank}") +``` + +**Change the numbers**: Try 100 gold among 7 members. What happens? + +### Challenge 3: Combo Multiplier + +Your combo system multiplies damage. Calculate the multiplier for different combo lengths: + +```python +# Base multiplier doubles with each hit +print(f"5-hit combo: {2 ** 5}x") # 32x +print(f"10-hit combo: {2 ** 10}x") # 1024x + +# What if it triples instead? +print(f"5-hit triple combo: {3 ** 5}x") # 243x +``` + +## Debugging With AI + +When your code gives unexpected results, here's how to get help: + +**"I got decimals but need whole numbers"** + +You want to split 20 power-ups among 6 players: + +```python +per_player = 20 / 6 +print(per_player) # 3.333... +``` + +Tell AI: *"I'm splitting 20 items among 6 players but getting 3.333. I need whole numbers."* + +AI will suggest using `//` (floor division) instead of `/`. + +**"I expected 8 but got 1"** + +You want 2 to the power of 3: + +```python +result = 2 ^ 3 +print(result) # 1 (not 8!) +``` + +Tell AI: *"I tried 2 ^ 3 expecting 8, but got 1. How do I calculate powers?"* + +AI will explain that Python uses `**` for powers, not `^`. + +**"My calculation gives the wrong answer"** + +You want to add two scores, then take 8%: + +```python +total = 100 + 100 * 0.08 +print(total) # 108 (not 16!) +``` + +Tell AI: *"I want (100 + 100) × 0.08 = 16, but I'm getting 108."* + +AI will explain that multiplication happens before addition, and show you how to use parentheses. + +## Try With AI + +**Explore edge cases:** +> "What happens when I divide by zero in Python? Show me 10 / 0 and 10 // 0. What error appears and why?" + +**Solve a real problem:** +> "I'm building a timer. I have 3661 seconds and need to convert to hours, minutes, and seconds. Which operators should I use? Show me step by step." + +**Understand precedence:** +> "Break down how Python evaluates: 2 ** 3 * 4 + 5. Show each step in order." diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/02-comparison-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/02-comparison-operators.md new file mode 100644 index 000000000..487fa58f1 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/02-comparison-operators.md @@ -0,0 +1,338 @@ +--- +title: "Comparison Operators" +sidebar_position: 2 +--- + +# Comparison Operators + +## What You'll Learn + +- Six Comparison Operators +- Equality vs Assignment +- Greater/Less Than Comparisons +- Boolean Results +- Common Comparison Patterns + +## The Problem + +Your game needs to check conditions: Did the player reach 100 points to win? Do they have enough health to survive? Is their score higher than the current high score? You're not calculating—you're asking yes/no questions. + +## Why You Need Comparison Operators + +Comparison operators ask questions and return answers: `True` or `False`. Without them, your game couldn't: + +- Check if player reached the winning score +- Verify if health dropped to zero (game over) +- Test if player beat the high score +- Make any decisions based on game state + +Every comparison gives you `True` or `False`. Let's discover how to ask these questions. + +## Checking Win Conditions + +Player has 85 points. They need 100 to win. Did they win? + +```python +score = 85 +win_threshold = 100 + +# Your prediction: What will this return? +player_won = score >= win_threshold +print(player_won) +``` + +**Run it.** You get `False`. The `>=` operator asks "is left side greater than or equal to right side?" and returns the answer. + +Now try other comparisons: + +```python +# Experiment: Try each comparison +a = 10 +b = 5 + +print(a == b) # Equal to - what do you get? +print(a != b) # Not equal to +print(a > b) # Greater than +print(a < b) # Less than +``` + +**What did you discover?** +- `==` checks equality (False - 10 is not equal to 5) +- `!=` checks inequality (True - 10 is different from 5) +- `>` checks greater than (True - 10 is greater than 5) +- `<` checks less than (False - 10 is not less than 5) + +**Important**: Notice `==` uses two equals signs. One `=` assigns a value, two `==` compares values. This is a common mistake. + +## The Six Comparison Operators + +### Equality and Inequality: Code Matching + +Player enters a secret code to unlock a bonus level. Did they enter the right code? + +```python +entered_code = 1234 +secret_code = 1234 + +# Check if they match +unlocked = entered_code == secret_code +print(unlocked) # What do you get? +``` + +You get `True`. Now check the opposite: + +```python +# Check if they're different +wrong_code = entered_code != secret_code +print(wrong_code) # What do you get? +``` + +You get `False`. They're not different—they match. + +**Pattern discovered**: `==` returns True if values match, `!=` returns True if values differ. + +### Greater Than and Less Than: Health Thresholds + +Player has 75 health. Is it above the danger threshold of 30? + +```python +health = 75 +danger_threshold = 30 + +# Is health above danger? +is_safe = health > danger_threshold +print(is_safe) # What do you get? +``` + +You get `True`. Now check if it's critical (below 10): + +```python +critical = 10 + +is_critical = health < critical +print(is_critical) # What do you get? +``` + +You get `False`. 75 is not less than 10. + +### Greater/Less Than OR Equal: Level Unlocks + +Player needs exactly 100 points or more to unlock the next level. + +```python +score = 100 +unlock_threshold = 100 + +# Does 100 unlock it? (must be 100 OR more) +unlocked = score >= unlock_threshold +print(unlocked) # What do you get? +``` + +You get `True`. The `>=` includes the equal case. + +**Try it**: What if score is 99? What about 101? + +```python +# Experiment with different scores +print(99 >= 100) # ? +print(100 >= 100) # ? +print(101 >= 100) # ? +``` + +**Pattern discovered**: `>=` and `<=` include the equal case, `>` and `<` exclude it. + +## Reference Table: All Six Operators + +| Operator | Name | Example | Result | Question Asked | +|----------|------|---------|--------|----------------| +| `==` | Equal | `5 == 5` | `True` | Are they the same? | +| `!=` | Not equal | `5 != 3` | `True` | Are they different? | +| `>` | Greater than | `5 > 3` | `True` | Is left bigger? | +| `<` | Less than | `5 < 3` | `False` | Is left smaller? | +| `>=` | Greater or equal | `5 >= 5` | `True` | Is left bigger or same? | +| `<=` | Less or equal | `5 <= 3` | `False` | Is left smaller or same? | + +## Comparisons Always Return Booleans + +Every comparison returns either `True` or `False`—these are called **boolean values**. + +```python +# All comparisons return True or False +result1 = 10 > 5 +result2 = 10 < 5 + +print(result1) # True +print(result2) # False +print(type(result1)) # What type is this? +``` + +You get ``. Boolean is Python's type for True/False values. + +**Why this matters**: In Chapter 18, you'll use these True/False values to make decisions with `if` statements. The comparison gives you the answer, the `if` acts on it. + +## Value Equality Surprises + +Is the integer 5 equal to the float 5.0? + +```python +int_five = 5 +float_five = 5.0 + +# Predict: True or False? +print(int_five == float_five) +``` + +**Surprising result**: You get `True`. Python compares **values**, not types. 5 and 5.0 represent the same value. + +Now try this: + +```python +int_five = 5 +string_five = "5" + +# Predict: True or False? +print(int_five == string_five) +``` + +You get `False`. The string "5" is text, not a number—completely different values. + +**Pattern discovered**: +- Same value, different numeric types → `True` (5 == 5.0) +- Different value types entirely → `False` (5 == "5") + +## Practice: Solve Real Problems + +### Challenge 1: Level Progression + +Check if player qualifies for different game milestones: + +```python +player_score = 85 + +# Bronze badge (50+) +bronze = player_score >= 50 +print(f"Bronze badge: {bronze}") + +# Silver badge (100+) +silver = player_score >= 100 +print(f"Silver badge: {silver}") + +# Gold badge (200+) +gold = player_score >= 200 +print(f"Gold badge: {gold}") +``` + +**Change the score**: Try 100, 200, and 45. What changes? + +### Challenge 2: Inventory Check + +Check if player has enough items. First, you need to know how many they have. + +**The `len()` function**: Python has a built-in function called `len()` that counts items in a list (or characters in a string). It returns a number. + +```python +# len() counts items +inventory = ["sword", "shield", "potion"] +item_count = len(inventory) +print(item_count) # 3 +``` + +Now use it with comparisons: + +```python +inventory = ["sword", "shield", "potion", "key", "map"] +required_items = 3 +max_capacity = 10 + +# Has enough items for quest? +ready_for_quest = len(inventory) >= required_items +print(f"Ready for quest: {ready_for_quest}") + +# Inventory full? +is_full = len(inventory) >= max_capacity +print(f"Inventory full: {is_full}") + +# Has room for more? +has_room = len(inventory) < max_capacity +print(f"Has room: {has_room}") +``` + +**Try it**: What if inventory has only 2 items? What if it has 10? + +### Challenge 3: High Score Check + +Check if player beat various records: + +```python +player_score = 850 +high_score = 1000 +personal_best = 850 + +# Beat the high score? +new_record = player_score > high_score +print(f"New high score: {new_record}") + +# Tied personal best? +tied_best = player_score == personal_best +print(f"Tied personal best: {tied_best}") + +# Below high score? +keep_trying = player_score < high_score +print(f"Keep trying: {keep_trying}") +``` + +## Debugging With AI + +When your comparisons give unexpected results, here's how to get help: + +**"I get a syntax error when checking equality"** + +You want to check if score equals 100: + +```python +score = 100 +if score = 100: # SyntaxError! + print("Won!") +``` + +Tell AI: *"I'm trying to check if score equals 100, but I get a syntax error."* + +AI will explain: Use `==` for comparison, not `=`. One equals sign assigns a value, two equals signs compare values. + +**"Score of 100 doesn't pass my check"** + +You want players with 100 or more to win: + +```python +score = 100 +won = score > 100 +print(won) # False (but 100 should win!) +``` + +Tell AI: *"A score of exactly 100 should win, but my check returns False."* + +AI will explain: `>` means "greater than" (excludes 100). Use `>=` for "greater than or equal to". + +**"My comparison is always False"** + +You compare user input to a number: + +```python +user_score = input("Enter score: ") # User types 100 +print(user_score == 100) # False (why?) +``` + +Tell AI: *"I typed 100 but the comparison to 100 is False."* + +AI will explain: `input()` returns text, not a number. `"100"` (text) is not the same as `100` (number). Convert it with `int()`. + +## Try With AI + +**Explore edge cases:** +> "What happens when I compare True to 1 and False to 0? Are booleans secretly numbers in Python?" + +**Solve a real problem:** +> "I'm building a thermostat. I need to check if temperature is below 60 (turn on heat), above 75 (turn on AC), or between (do nothing). What comparisons do I need?" + +**Understand the difference:** +> "Explain why `=` and `==` exist as separate operators. Show me what goes wrong if I accidentally use the wrong one." diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/03-logical-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/03-logical-operators.md new file mode 100644 index 000000000..c7d1bd785 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/03-logical-operators.md @@ -0,0 +1,332 @@ +--- +title: "Logical Operators" +sidebar_position: 3 +--- + +# Logical Operators + +## What You'll Learn + +- Three Logical Operators +- Combining Conditions with `and` +- Alternative Conditions with `or` +- Inverting with `not` +- Truth Tables + +## The Problem + +Your game has complex rules. To enter the boss level, the player must have score >= 100 AND health > 0. To use a special attack, they need mana >= 50 OR have a power potion. One comparison isn't enough—you need to combine conditions. + +## Why You Need Logical Operators + +Logical operators combine True/False values to make complex decisions. Without them, your game couldn't: + +- Check win conditions (score >= 100 AND lives > 0) +- Allow alternative abilities (has sword OR has magic) +- Block defeated players (NOT alive) +- Express complex game rules + +Instead of asking one question, you can ask: "Is this true AND that true?" or "Is this true OR that true?" Let's discover how. + +## Combining Conditions for Boss Entry + +To enter the boss level, player needs score >= 100 AND health > 0. Can this player enter? + +```python +score = 120 +health = 50 + +# Your prediction: What will this return? +can_enter_boss = score >= 100 and health > 0 +print(can_enter_boss) +``` + +**Run it.** You get `True`. The `and` operator returns True only when BOTH conditions are True. + +Now change the values: + +```python +score = 120 +health = 0 # Player is defeated + +can_enter_boss = score >= 100 and health > 0 +print(can_enter_boss) # What now? +``` + +You get `False`. Even though score is high enough, health is zero. Both must be true. + +## The Three Logical Operators + +### The `and` Operator: Unlocking Treasure Chests + +To unlock the treasure chest, player needs key AND lockpick skill >= 5. + +```python +has_key = True +lockpick_skill = 7 + +# Both conditions must be true +can_open = has_key and lockpick_skill >= 5 +print(can_open) # What do you get? +``` + +You get `True`. Both conditions are met. + +**Experiment**: What happens when one condition fails? + +```python +# Test different combinations +print(True and True) # ? +print(True and False) # ? +print(False and True) # ? +print(False and False) # ? +``` + +**Pattern discovered**: `and` returns True ONLY when both sides are True. + +### The `or` Operator: Alternative Attack Methods + +Player can attack if they have sword OR magic spell available. + +```python +has_sword = False +has_magic = True + +# At least one must be true +can_attack = has_sword or has_magic +print(can_attack) # What do you get? +``` + +You get `True`. They have magic, so they can attack. + +**Experiment**: What happens with different combinations? + +```python +# Test different combinations +print(True or True) # ? +print(True or False) # ? +print(False or True) # ? +print(False or False) # ? +``` + +**Pattern discovered**: `or` returns True when AT LEAST ONE side is True. Only False when both are False. + +### The `not` Operator: Checking Movement Status + +Player can move if they are NOT frozen. + +```python +is_frozen = False + +# Flip the value +can_move = not is_frozen +print(can_move) # What do you get? +``` + +You get `True`. The player is not frozen, so they can move. + +**Experiment**: What does `not` do to each value? + +```python +print(not True) # ? +print(not False) # ? +``` + +**Pattern discovered**: `not` flips True to False and False to True. + +## Reference Table: Truth Tables + +### `and` - Both must be True + +| A | B | A and B | +|---|---|---------| +| True | True | **True** | +| True | False | False | +| False | True | False | +| False | False | False | + +### `or` - At least one must be True + +| A | B | A or B | +|---|---|--------| +| True | True | **True** | +| True | False | **True** | +| False | True | **True** | +| False | False | False | + +### `not` - Flip the value + +| A | not A | +|---|-------| +| True | False | +| False | **True** | + +## Combining Multiple Conditions: Raid Requirements + +You can chain logical operators together. + +To start a raid, player needs (level >= 10 OR has party) AND has quest item. + +```python +level = 5 +has_party = True +has_quest_item = True + +# Complex condition +can_raid = (level >= 10 or has_party) and has_quest_item +print(can_raid) # What do you get? +``` + +You get `True`. They're under level 10 but have a party, and they have the quest item. + +**Try removing the quest item**: + +```python +has_quest_item = False +can_raid = (level >= 10 or has_party) and has_quest_item +print(can_raid) # What now? +``` + +You get `False`. The first part is True (has party), but no quest item means the whole thing is False. + +**Important**: Use parentheses to make your logic clear. Without them, Python follows precedence rules that might surprise you. + +## Short-Circuit Evaluation: Python's Smart Optimization + +Python is smart about evaluating logical operators: + +```python +# With 'and', if first is False, Python doesn't check second +x = False +result = x and (10 / 0) # No error! Python stops at False +print(result) # False + +# With 'or', if first is True, Python doesn't check second +y = True +result = y or (10 / 0) # No error! Python stops at True +print(result) # True +``` + +**Why this matters**: You can use this to avoid errors: + +```python +# Safe division +denominator = 0 + +# This is safe - Python won't divide if denominator is 0 +is_large_result = denominator != 0 and 10 / denominator > 2 +print(is_large_result) # False (never attempted the division) + +# Try with a valid denominator +denominator = 2 +is_large_result = denominator != 0 and 10 / denominator > 2 +print(is_large_result) # True (10/2 = 5, which is > 2) +``` + +The first check stops at `denominator != 0` (False), so Python never evaluates `10 / denominator`—avoiding the division-by-zero error. + +## Practice: Solve Real Problems + +### Challenge 1: Boss Fight Entry + +Check if player can enter the boss fight: + +```python +is_champion = False +level = 15 +has_key = True + +# Champion enters automatically +# Others need level >= 10 AND key +can_fight_boss = is_champion or (level >= 10 and has_key) +print(f"Can fight boss: {can_fight_boss}") +``` + +**Experiment**: What if level is 15 but has_key is False? + +### Challenge 2: Loot Drop Bonus + +Player gets bonus loot if: is_VIP OR in_guild OR score > 1000. + +```python +is_vip = False +in_guild = False +score = 1500 + +# Any of these conditions qualifies +gets_bonus = is_vip or in_guild or score > 1000 +print(f"Gets bonus loot: {gets_bonus}") +``` + +**Change values**: What combination gives False? + +### Challenge 3: Valid Character Name + +Character name must be: not empty AND between 3-15 characters. + +```python +name = "DragonSlayer" + +# Check all conditions +is_valid = len(name) > 0 and len(name) >= 3 and len(name) <= 15 +print(f"Valid name: {is_valid}") + +# Cleaner way using chained comparison +is_valid = len(name) > 0 and 3 <= len(name) <= 15 +print(f"Valid name: {is_valid}") +``` + +## Debugging With AI + +When your logical conditions give unexpected results, here's how to get help: + +**"My condition is always False"** + +You want to check if player qualifies for special rate (under 18 or over 65): + +```python +age = 25 +special_rate = age < 18 and age > 65 +print(special_rate) # Always False! +``` + +Tell AI: *"I want players under 18 OR over 65 to get special rate, but it's always False."* + +AI will explain: You used `and`, which requires BOTH conditions. No one can be under 18 AND over 65 at the same time! Use `or` instead. + +**"The result isn't what I expected"** + +You want to check: (can attack OR can defend) AND has energy: + +```python +result = True or False and False +print(result) # True (expected False!) +``` + +Tell AI: *"I want (True or False) and False, which should be False, but I'm getting True."* + +AI will explain: Python evaluates `and` before `or`. Add parentheses to control the order: `(True or False) and False`. + +**"This logic is confusing"** + +Your variable names make the code hard to read: + +```python +is_not_invalid = not is_invalid +``` + +Tell AI: *"This double negative is confusing. How can I make it clearer?"* + +AI will suggest: Use positive names like `is_valid = not is_invalid`, or better yet, design with positive names from the start. + +## Try With AI + +**Explore short-circuit:** +> "Explain Python's short-circuit evaluation for `and` and `or`. When does Python skip evaluating the second operand? Show examples where this prevents errors." + +**Solve a real problem:** +> "I'm building a game. Player can move if: not frozen AND (has stamina OR has energy potion). Write the logical expression and test it with different True/False combinations." + +**Understand precedence:** +> "What's the precedence order for `not`, `and`, `or`? Show how `not True or False and True` is evaluated step by step." + diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/04-assignment-operators.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/04-assignment-operators.md new file mode 100644 index 000000000..0706925ce --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/04-assignment-operators.md @@ -0,0 +1,367 @@ +--- +title: "Assignment Operators" +sidebar_position: 4 +--- + +# Assignment Operators + +## What You'll Learn + +- Five Assignment Operators +- Shorthand vs Expanded Form +- Counter and Accumulator Patterns +- Common Update Operations + +## The Problem + +You're building a game score tracker. The player starts with 100 points, collects 50 more, loses 25, then doubles their score with a power-up. You need to update the same variable multiple times. + +## Why You Need Assignment Operators + +Assignment operators are shortcuts for updating variables. Without them, you'd write `score = score + 50` every time. With them, you write `score += 50`. This matters because: + +- Cleaner code that's easier to read +- Less typing and fewer mistakes +- Standard patterns everyone recognizes (counters, accumulators) +- Expresses intent clearly: "add to this variable" + +Let's discover the shortcuts. + +## Tracking Player Health + +You're tracking a player's health. It starts at 100, and they take 25 damage. How do you update it? + +```python +health = 100 + +# Long way +health = health - 25 +print(health) # What do you get? +``` + +You get `75`. But there's a shorter way: + +```python +health = 100 + +# Short way +health -= 25 +print(health) # What do you get? +``` + +Same result: `75`. The `-=` operator subtracts and assigns in one step. + +**Pattern discovered**: `variable -= value` is the same as `variable = variable - value`. + +## The Five Assignment Operators + +### Addition Assignment: Counting Visitors + +You're counting website visitors. Each visit adds 1 to the counter. + +```python +visitors = 0 + +# A visitor arrives +visitors += 1 +print(visitors) # What do you get? + +# Another visitor +visitors += 1 +print(visitors) # What now? + +# Five more visitors +visitors += 5 +print(visitors) # Final count? +``` + +You get `1`, then `2`, then `7`. The `+=` operator adds to the current value. + +**Equivalence**: +```python +# These do the same thing: +count = count + 1 +count += 1 +``` + +### Subtraction Assignment: Managing Inventory + +You're tracking inventory. You have 50 items and sell 12. + +```python +inventory = 50 + +# Sell items +inventory -= 12 +print(inventory) # What's left? + +# Sell more +inventory -= 8 +print(inventory) # Now? +``` + +You get `38`, then `30`. + +### Multiplication Assignment: Compound Growth + +You're calculating compound growth. A value doubles each round. + +```python +value = 1 + +# Round 1: double it +value *= 2 +print(value) # ? + +# Round 2: double again +value *= 2 +print(value) # ? + +# Round 3: double again +value *= 2 +print(value) # ? +``` + +You get `2`, then `4`, then `8`. + +**Real use case**: Applying percentage increases: + +```python +price = 100 + +# Apply 10% markup +price *= 1.10 +print(price) # 110.0 +``` + +### Division Assignment: Splitting Bills + +You're splitting a bill. Total is $120 among 4 people. + +```python +total = 120 + +# Split among 4 +total /= 4 +print(total) # What does each person pay? +``` + +You get `30.0`. Notice it's a float, even though 120 divides evenly by 4. + +**Important**: `/=` always produces a float, just like `/`. + +### Floor Division Assignment: Whole Number Results + +You need whole number results when dividing. + +```python +items = 25 +boxes = 4 + +# How many items per box (whole numbers only)? +items //= boxes +print(items) # ? +``` + +You get `6`. Floor division drops the decimal. + +## Reference Table: All Assignment Operators + +| Operator | Name | Example | Equivalent To | +|----------|------|---------|---------------| +| `=` | Assign | `x = 5` | — | +| `+=` | Add assign | `x += 3` | `x = x + 3` | +| `-=` | Subtract assign | `x -= 3` | `x = x - 3` | +| `*=` | Multiply assign | `x *= 3` | `x = x * 3` | +| `/=` | Divide assign | `x /= 3` | `x = x / 3` | +| `//=` | Floor divide assign | `x //= 3` | `x = x // 3` | + +## Common Patterns in Games + +### The Counter Pattern + +The most common use of `+=` is counting things: + +```python +count = 0 + +# Process items one by one +count += 1 +print(f"Processed {count}: apple") + +count += 1 +print(f"Processed {count}: banana") + +count += 1 +print(f"Processed {count}: cherry") + +print(f"Total: {count}") +``` + +You'll use `count += 1` constantly when you learn loops in Chapter 18—that's when you'll automate this pattern instead of writing each line manually. + +### The Accumulator Pattern + +Adding up values as you go: + +```python +total = 0 + +# Add up prices one by one +total += 10.50 +print(f"Running total: ${total:.2f}") + +total += 20.00 +print(f"Running total: ${total:.2f}") + +total += 15.75 +print(f"Running total: ${total:.2f}") + +print(f"Final total: ${total:.2f}") +``` + +### The Multiplier Pattern + +Applying repeated multiplications: + +```python +# Compound interest: 5% growth for 3 years +principal = 1000 +rate = 1.05 + +principal *= rate # Year 1 +print(f"After year 1: ${principal:.2f}") + +principal *= rate # Year 2 +print(f"After year 2: ${principal:.2f}") + +principal *= rate # Year 3 +print(f"After year 3: ${principal:.2f}") +``` + +## Practice: Solve Real Problems + +### Challenge 1: Game Score Tracker + +Track a player's score through various events: + +```python +score = 0 + +# Collect coins (+10 each) +score += 10 +score += 10 +score += 10 +print(f"After coins: {score}") + +# Hit by enemy (-15) +score -= 15 +print(f"After hit: {score}") + +# Power-up doubles score +score *= 2 +print(f"After power-up: {score}") +``` + +**Extend it**: Add more events. What's the final score? + +### Challenge 2: Health and Mana + +Track player resources during combat: + +```python +health = 100 +mana = 50 + +# Take damage (-30) +health -= 30 +print(f"After hit: Health={health}") + +# Use healing spell (costs 20 mana, restores 25 health) +mana -= 20 +health += 25 +print(f"After heal: Health={health}, Mana={mana}") + +# Drink mana potion (+40 mana) +mana += 40 +print(f"After potion: Health={health}, Mana={mana}") +``` + +### Challenge 3: Experience and Leveling + +Track XP with multipliers: + +```python +xp = 0 + +# Defeat enemies (+50 each) +xp += 50 +xp += 50 +xp += 50 +print(f"After enemies: {xp} XP") + +# Apply XP boost (double) +xp *= 2 +print(f"After boost: {xp} XP") + +# Complete quest (+100) +xp += 100 +print(f"After quest: {xp} XP") +``` + +## Debugging With AI + +When your variable updates don't work as expected, here's how to get help: + +**"The variable isn't changing"** + +You want to subtract 10 from the score: + +```python +score = 100 +score - 10 +print(score) # Still 100! +``` + +Tell AI: *"I subtracted 10 from score but it's still 100."* + +AI will explain: `score - 10` calculates the result but doesn't save it anywhere. You need `score = score - 10` or the shortcut `score -= 10`. + +**"I'm getting decimals instead of whole numbers"** + +You want to split 10 coins between 2 players: + +```python +coins = 10 +coins /= 2 +print(coins) # 5.0 (not 5) +``` + +Tell AI: *"I divided coins by 2 but got 5.0 instead of 5. I want a whole number."* + +AI will explain: `/=` always gives decimals. Use `//=` for whole number results. + +**"I'm confused about = vs =="** + +You want to check if score equals 100: + +```python +score = 100 +is_winner = score = 100 # This is assignment, not comparison! +print(is_winner) # Prints 100, not True or False +``` + +Tell AI: *"I want to check if score equals 100 but I used = instead of ==."* + +AI will explain: `=` assigns a value, `==` checks equality. Use `is_winner = score == 100` to get True or False. + +## Try With AI + +**Explore equivalence:** +> "Show me that `x += 5` and `x = x + 5` do exactly the same thing. Are there any cases where they behave differently?" + +**Solve a real problem:** +> "I'm building a fitness tracker. I need to track: steps (add each walk), calories (subtract each meal), and distance (accumulate). Show me how to use assignment operators for each." + +**Understand types:** +> "What happens to the type when I use `/=` on an integer? Why does `//=` keep it as an integer? Show examples." diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/05-keywords.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/05-keywords.md new file mode 100644 index 000000000..603738a34 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/05-keywords.md @@ -0,0 +1,363 @@ +--- +title: "Python Keywords" +sidebar_position: 5 +--- + +# Python Keywords + +## What You'll Learn + +- What Keywords Are +- Reserved Words You Can't Use as Variables +- Categories of Keywords +- Common Keyword Uses + +## The Problem + +You try to name a variable `class` or `for`, but Python gives you a syntax error. Why can't you use these perfectly good words? + +## Why Keywords Matter + +Keywords are reserved words that Python uses for its own syntax. You cannot use them as variable names, function names, or any other identifier. Understanding keywords helps you: + +- Avoid naming conflicts +- Understand Python's structure +- Read code more effectively +- Recognize syntax patterns + +Let's discover what words Python reserves for itself. + +## What Are Keywords? + +Keywords are special words that Python has reserved for specific purposes. They define the structure and logic of Python programs. + +```python +# You CANNOT do this - these are keywords +# class = "Math" # SyntaxError! +# for = 10 # SyntaxError! +# if = True # SyntaxError! + +# You CAN use descriptive alternatives +course_class = "Math" +loop_count = 10 +is_valid = True +``` + +**Key Point**: Keywords are case-sensitive. `True` is a keyword, but `true` is not (though using `true` would be confusing). + +## How to See All Keywords + +Python provides a way to list all keywords: + +```python +import keyword + +# Get the list of all keywords +all_keywords = keyword.kwlist +print(f"Python has {len(all_keywords)} keywords") +print(all_keywords) +``` + +Output: +``` +Python has 35 keywords +['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', + 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', + 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', + 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', + 'try', 'while', 'with', 'yield'] +``` + +## Keywords by Category + +### Value Keywords + +These represent specific values: + +```python +# Boolean values +is_active = True +is_deleted = False + +# Absence of value +result = None # No value assigned yet + +# Check types +print(type(True)) # +print(type(False)) # +print(type(None)) # +``` + +### Logical Operator Keywords + +You already learned these in Lesson 3: + +```python +# and - both must be True +can_enter = is_member and has_ticket + +# or - at least one must be True +gets_discount = is_student or is_senior + +# not - inverts the value +is_invalid = not is_valid +``` + +### Membership and Identity Keywords + +```python +# in - check if item exists in collection +numbers = [1, 2, 3, 4, 5] +has_three = 3 in numbers +print(f"Contains 3: {has_three}") # True + +# not in - check if item doesn't exist +has_ten = 10 in numbers +print(f"Contains 10: {has_ten}") # False + +# is - check if same object (identity) +a = None +is_none = a is None +print(f"Is None: {is_none}") # True + +# is not - check if different object +b = 5 +is_not_none = b is not None +print(f"Is not None: {is_not_none}") # True +``` + +### Control Flow Keywords (Preview) + +You'll learn these in detail in Chapter 18: + +```python +# if, elif, else - conditional branching +# for, while - loops +# break, continue - loop control +# pass - placeholder that does nothing +``` + +### Function and Class Keywords (Preview) + +You'll learn these in later chapters: + +```python +# def - define a function (Chapter 21) +# return - return a value from function (Chapter 21) +# class - define a class (Chapter 25) +# lambda - create anonymous function (Chapter 21) +``` + +### Import Keywords + +```python +# import - bring in a module +import math + +# from - import specific items from a module +from math import pi, sqrt + +# as - give an alias +import math as m +``` + +### Exception Keywords (Preview) + +You'll learn these in Chapter 22: + +```python +# try, except, finally - handle errors +# raise - create an error +# assert - debugging check +``` + +## Keywords You'll Use Most Often + +### True, False, None + +The most fundamental keywords: + +```python +# Booleans for conditions +is_logged_in = True +has_permission = False + +# None for "no value" +user_input = None # Will be filled later +search_result = None # Nothing found +``` + +### and, or, not + +For combining conditions (Lesson 3): + +```python +# Complex conditions +can_vote = age >= 18 and is_citizen +gets_bonus = is_vip or score > 1000 +is_active = not is_deleted +``` + +### in, not in + +For checking membership: + +```python +# Check if value exists +valid_grades = ["A", "B", "C", "D", "F"] +grade = "B" +is_valid = grade in valid_grades +print(f"Valid grade: {is_valid}") # True + +# Check if value is missing +missing = "Z" not in valid_grades +print(f"Z is not valid: {missing}") # True +``` + +### is, is not + +For identity checking (especially with None): + +```python +# The correct way to check for None +value = None + +# Good - use 'is' for None +is_empty = value is None +print(f"Is None: {is_empty}") # True + +# Also good +has_value = value is not None +print(f"Has value: {has_value}") # False +``` + +**Important**: Use `is` for `None`, `True`, `False`. Use `==` for other value comparisons. + +```python +# Correct usage +x = None +check1 = x is None # Good for None + +y = 5 +check2 = y == 5 # Good for values +``` + +## Checking if a Word is a Keyword + +```python +import keyword + +# Check specific words +print(keyword.iskeyword("for")) # True +print(keyword.iskeyword("print")) # False (it's a built-in function, not keyword) +print(keyword.iskeyword("score")) # False (valid variable name) +print(keyword.iskeyword("class")) # True +``` + +## Common Naming Mistakes + +### Mistake 1: Using Keywords as Variables + +```python +# WRONG - these cause SyntaxError +# class = "Biology" +# for = 10 +# import = "data.csv" + +# RIGHT - use descriptive alternatives +course_class = "Biology" +iteration_count = 10 +import_file = "data.csv" +``` + +### Mistake 2: Shadowing Built-in Functions + +While not keywords, avoid using these names too: + +```python +# AVOID - shadows built-in functions +# list = [1, 2, 3] # Now you can't use list() +# str = "hello" # Now you can't use str() +# print = "output" # Now you can't use print() + +# BETTER - use descriptive names +numbers_list = [1, 2, 3] +greeting_str = "hello" +output_text = "output" +``` + +### Mistake 3: Case Sensitivity + +```python +# These are different! +true = "this is a string" # Valid variable (but confusing!) +# True = "this is a string" # SyntaxError! True is a keyword + +# Don't do this - it's confusing +none = "something" # Valid but terrible practice +# None = "something" # SyntaxError! None is a keyword +``` + +## Practice: Identify the Keywords + +Look at this code and identify all keywords: + +```python +import math + +is_positive = True +value = None + +has_value = value is not None +in_range = 0 in [0, 1, 2] and is_positive + +pi_value = math.pi +``` + +**Keywords used**: `import`, `True`, `None`, `is`, `not`, `in`, `and` + +## Reference: All 35 Python Keywords + +| Category | Keywords | +|----------|----------| +| Values | `True`, `False`, `None` | +| Logical | `and`, `or`, `not` | +| Membership/Identity | `in`, `is` | +| Control Flow | `if`, `elif`, `else`, `for`, `while`, `break`, `continue`, `pass` | +| Functions | `def`, `return`, `lambda`, `yield` | +| Classes | `class` | +| Imports | `import`, `from`, `as` | +| Exceptions | `try`, `except`, `finally`, `raise`, `assert` | +| Context | `with` | +| Async | `async`, `await` | +| Scope | `global`, `nonlocal` | +| Other | `del` | + +## Debugging With AI + +**"I can't use this variable name"** + +```python +class = "Math 101" # SyntaxError! +``` + +Tell AI: *"I tried to name my variable 'class' but got a SyntaxError."* + +AI will explain: `class` is a reserved keyword. Use `course_class`, `class_name`, or another descriptive name instead. + +**"What's the difference between is and =="** + +Tell AI: *"When should I use 'is' vs '==' in Python?"* + +AI will explain: Use `is` for identity (same object) and checking `None`. Use `==` for value equality. + +## Try With AI + +**Explore keywords:** +> "List all Python keywords and group them by what they're used for. Which ones are most important for beginners? Which ones will I learn later?" + +**Understand identity vs equality:** +> "Explain the difference between `x is None` and `x == None`. Why is `is` preferred for None? Show examples where `is` and `==` give different results." + +**Check your names:** +> "I want to name my variables: list, type, input, for, score, class_name. Which of these are bad choices and why?" diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/06-capstone.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/06-capstone.md new file mode 100644 index 000000000..32dfce9d1 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/06-capstone.md @@ -0,0 +1,161 @@ +--- +title: "Capstone: Game Score System" +sidebar_position: 6 +--- + +# Capstone: Game Score System + +## What You'll Build + +- Complete Game Score System +- All Four Operator Types Combined +- Win/Lose Condition Checking +- Score Tracking and Bonuses + +## The Challenge + +You've learned arithmetic, comparison, logical, and assignment operators separately—all using game examples. Now combine them into one working game score system. + +Build a game score system that demonstrates all four operator types working together. + +### Requirements + +Your game system must: + +1. **Get player stats from user** using `input()` (score and health) +2. **Calculate bonuses** using arithmetic: coin bonus, combo multiplier +3. **Check win/lose conditions** using comparisons: score threshold, health check +4. **Validate game state** with logical operators: can continue playing +5. **Update running totals** using assignment operators +6. **Handle edge cases** safely (e.g., division for team splits) + +### Expected Output + +When the user enters score `85` and health `50`, your program should display something like: + +``` +======================================== +GAME SCORE SYSTEM +======================================== + +Enter your score: 85 +Enter your health: 50 + +--- SCORE CALCULATIONS --- +Base score: 85 +Coin bonus (10 coins × 5): 50 +Total with bonus: 135 +With 2x combo multiplier: 270 + +--- WIN/LOSE CONDITIONS --- +Final score >= 100 to win: True +Health > 0 (alive): True +Final score >= high score (200): True + +--- GAME STATE --- +Can continue (base score >= 50 AND health > 0): True +Gets bonus loot (final score > 100 OR health == 100): True + +--- RUNNING TOTALS --- +Starting total: 0 +After adding score: 270 +After enemy hit (-20): 250 +After power-up (×1.5): 375.0 + +======================================== +Game complete! +======================================== +``` + +## Hints + +
+Hint 1: Getting player stats from user + +Use `input()` and convert to int: +```python +score = int(input("Enter your score: ")) +health = int(input("Enter your health: ")) +``` +
+ +
+Hint 2: Score calculations (arithmetic) + +Store results in variables: +```python +coin_bonus = 10 * 5 # 10 coins worth 5 each +total = score + coin_bonus +final_score = total * 2 # combo multiplier +``` +
+ +
+Hint 3: Win/lose conditions (comparisons) + +Comparisons return True or False: +```python +won = score >= 100 +alive = health > 0 +print(f"Won: {won}") +``` +
+ +
+Hint 4: Game state (logical) + +Combine conditions with `and` and `or`: +```python +can_continue = (score >= 50) and (health > 0) +gets_bonus = (score > 100) or (health == 100) +``` +
+ +
+Hint 5: Running totals (assignment) + +Update a variable step by step: +```python +total = 0 +total += final_score +total -= 20 # enemy damage +total *= 1.5 # power-up +``` +
+ +
+Hint 6: Safe team split + +For now, assume team_size is never 0: +```python +team_size = 4 +per_player = total / team_size +print(f"Each player gets: {per_player}") +``` + +**Note**: To handle the case where team_size might be 0, you'll need `if/else` statements—which you'll learn in Chapter 18. For this capstone, use a non-zero team size. +
+ +## Testing Your Game System + +Test with these input combinations: + +| Test Case | Score | Health | What to Check | +|-----------|-------|--------|---------------| +| Normal win | 85 | 50 | All conditions and calculations work | +| Low score | 30 | 100 | Can't continue (score < 50) | +| Zero health | 100 | 0 | Game over (health check fails) | +| Perfect game | 200 | 100 | Gets bonus loot (health == 100) | +| Edge case | 50 | 1 | Minimum to continue playing | + +## Success Criteria + +Your game system is complete when: + +- [ ] Gets score and health from user input +- [ ] Calculates bonuses using arithmetic (+, *, /) +- [ ] Checks win/lose conditions with comparisons (>=, >, ==) +- [ ] Uses `and` and `or` for game state logic +- [ ] Tracks running total with +=, -=, *= +- [ ] Calculates team split (assumes non-zero team size) +- [ ] Displays clear, formatted output with sections diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/06_chapter_16_quiz.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/06_chapter_16_quiz.md similarity index 100% rename from book-source/docs/04-Python-Fundamentals/16-operators-keywords-variables/06_chapter_16_quiz.md rename to book-source/docs/04-Python-Fundamentals/16-operators-keywords/06_chapter_16_quiz.md diff --git a/book-source/docs/04-Python-Fundamentals/16-operators-keywords/README.md b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/README.md new file mode 100644 index 000000000..47b220a72 --- /dev/null +++ b/book-source/docs/04-Python-Fundamentals/16-operators-keywords/README.md @@ -0,0 +1,64 @@ +--- +sidebar_position: 16 +title: "Chapter 16: Operators and Keywords" +--- + +# Chapter 16: Operators and Keywords + +In the previous chapters, you learned about data types and how to store values in variables. Now it's time to learn what you can DO with that data using operators—the symbols that tell Python to perform actions—and understand which words Python reserves for itself. + +Operators are the verbs of programming. Data types are the nouns (what you work with). Operators are the verbs (what you do with them). Keywords are special words Python reserves for its own syntax. Together, they let you build calculations, make decisions, and update values. + +## What You'll Master + +- Arithmetic Operators +- Comparison Operators +- Logical Operators +- Assignment Operators +- Python Keywords +- Capstone Game Score System + +## Chapter Structure + +### Lesson 1: Arithmetic Operators +Discover Python's seven arithmetic operators through problem-solving. You'll calculate fuel usage, distribute items into groups, and find remainders—all skills you'll use constantly. + +**Topics**: `+`, `-`, `*`, `/`, `//`, `%`, `**`, operator precedence + +### Lesson 2: Comparison Operators +Learn to ask True/False questions. Is this password correct? Is the user old enough? Is this value within range? Comparisons are the foundation for all decision-making in code. + +**Topics**: `==`, `!=`, `>`, `<`, `>=`, `<=`, boolean results + +### Lesson 3: Logical Operators +Combine multiple conditions into complex decisions. Must be 18 AND have a license. Can pay with credit OR debit. These operators let you express real-world logic. + +**Topics**: `and`, `or`, `not`, truth tables, short-circuit evaluation + +### Lesson 4: Assignment Operators +Update variables efficiently with shortcuts. Instead of `score = score + 10`, write `score += 10`. Cleaner, faster, and the standard pattern for counters and accumulators. + +**Topics**: `=`, `+=`, `-=`, `*=`, `/=`, counter pattern, accumulator pattern + +### Lesson 5: Python Keywords +Understand which words Python reserves for itself. You can't use `class`, `for`, or `True` as variable names—they're part of Python's syntax. + +**Topics**: Reserved words, `True`/`False`/`None`, `in`/`is`, keyword categories, naming best practices + +### Lesson 6: Capstone - Game Score System +Build a complete game score system that uses all four operator types plus keywords. Get user input, perform calculations, validate with comparisons, combine conditions with logic, and track running totals. + +**Challenge**: Integrate arithmetic, comparison, logical, and assignment operators into one working program. + +## Prerequisites + +Before starting this chapter, you should be comfortable with: +- Variables and assignment (Chapter 14) +- Basic data types: int, float, bool, str (Chapter 15) +- The `print()` and `input()` functions (Chapter 14) + +## What's Next + +After mastering operators, you'll move on to: +- **Chapter 17: Strings & Type Casting** — Text manipulation and converting between types +- **Chapter 18: Control Flow & Loops** — Using comparison and logical operators in `if` statements and loops diff --git a/history/audits/chapter-16-operators-fact-check-2025-11-22.md b/history/audits/chapter-16-operators-fact-check-2025-11-22.md new file mode 100644 index 000000000..ddf6fde2b --- /dev/null +++ b/history/audits/chapter-16-operators-fact-check-2025-11-22.md @@ -0,0 +1,514 @@ +# Factual Verification Report: Chapter 16 (Operators & Keywords & Variables) + +**Content**: Chapter 16: Operators, Keywords & Variables +**Files Verified**: +- 01-arithmetic-operators.md +- 02-comparison-operators.md +- 03-logical-operators.md +- 04-assignment-operators.md +- 05-keywords-capstone.md + +**Date**: 2025-11-22 +**Verification Coverage**: 42 verified / 42 total claims (100%) + +--- + +## Executive Summary + +All technical claims in Chapter 16 are **FACTUALLY ACCURATE**. Python operator behavior, precedence rules, type coercion, and all code examples produce correct outputs. No false claims, misleading statements, or syntax errors detected. Content is suitable for A2-level learners with proper scaffolding. + +**Overall Verdict**: VERIFIED ✅ + +--- + +## Verified Claims (42/42) + +### ARITHMETIC OPERATORS LESSON (01-arithmetic-operators.md) + +#### Claim 1: Addition Works Like Math Class +**Claim**: "The `+` symbol works exactly like math class" +**Source**: [Python Language Reference - Arithmetic operations, 2025] +**Verification Method**: Tested `50 + 30 = 80` +**Status**: ✅ VERIFIED +**Notes**: Correct for numeric types + +#### Claim 2: Division Always Returns Float +**Claim**: "`/` divides (3.333...) ... `/` gives decimal results" +**Source**: [PEP 238 - Python 3.0 Division Semantics, 2001] +**Verification Method**: Tested `10 / 2 = 5.0` (returns float), `10 / 3 = 3.3333...` +**Status**: ✅ VERIFIED +**Notes**: Critical distinction from Python 2 where `/` was integer division. Python 3 true division always returns float. + +#### Claim 3: Floor Division Drops Decimal +**Claim**: "`//` operator divides and drops the decimal" +**Source**: [Python Documentation - Numeric Types] +**Verification Method**: Tested `20 // 6 = 3`, `10 // 3 = 3` +**Status**: ✅ VERIFIED +**Notes**: Accurate description; floors toward negative infinity + +#### Claim 4: Modulus Returns Remainder +**Claim**: "The `%` operator gives the remainder" +**Source**: [Python Language Reference - Arithmetic operations] +**Verification Method**: Tested `20 % 6 = 2`, `17 % 5 = 2`, `10 % 3 = 1` +**Status**: ✅ VERIFIED + +#### Claim 5: Modulus for Even Check +**Claim**: "Check if even: `number % 2` gives 0 if even" +**Source**: [Common Programming Pattern] +**Verification Method**: Tested `10 % 2 = 0` +**Status**: ✅ VERIFIED + +#### Claim 6: Exponentiation with ** +**Claim**: "The `** ` operator raises numbers to powers" +**Source**: [Python Language Reference - Arithmetic operations] +**Verification Method**: Tested `2 ** 8 = 256`, `3 ** 2 = 9`, `5 ** 0 = 1` +**Status**: ✅ VERIFIED + +#### Claim 7: Caret Does NOT Mean Power +**Claim**: "Don't use `^` for powers—it does something else in Python" +**Source**: [Python Language Reference - Bitwise Operations] +**Verification Method**: Tested `2 ^ 3 = 1` (XOR), `2 ** 3 = 8` (power) +**Status**: ✅ VERIFIED +**Notes**: `^` is bitwise XOR operator; critical distinction for beginners + +#### Claim 8: PEMDAS Precedence Applies +**Claim**: "Python follows math rules: multiplication before addition" +**Source**: [Python Language Reference - Operator Precedence] +**Verification Method**: Tested `2 + 3 * 4 = 14` (not 20) +**Status**: ✅ VERIFIED + +#### Claim 9: Parentheses Control Order +**Claim**: "Use parentheses to change the order... `(2 + 3) * 4 = 20`" +**Source**: [Python Language Reference - Operator Precedence] +**Verification Method**: Tested `(2 + 3) * 4 = 20` +**Status**: ✅ VERIFIED + +#### Claim 10: Reference Table - All Seven Operators +**Claim**: Reference table with operators `+`, `-`, `*`, `/`, `//`, `%`, `**` and results +**Source**: [Python Language Reference - Arithmetic operations] +**Verification Method**: All examples tested and verified +**Status**: ✅ VERIFIED +**Results Match**: +- `10 + 3 = 13` ✓ +- `10 - 3 = 7` ✓ +- `10 * 3 = 30` ✓ +- `10 / 3 = 3.333...` ✓ +- `10 // 3 = 3` ✓ +- `10 % 3 = 1` ✓ +- `10 ** 3 = 1000` ✓ + +--- + +### COMPARISON OPERATORS LESSON (02-comparison-operators.md) + +#### Claim 11: Equality vs Assignment Distinction +**Claim**: "`==` uses two equals signs. One `=` assigns a value, two `==` compares values" +**Source**: [Python Language Reference - Assignment vs Comparison] +**Verification Method**: Demonstrated syntax difference +**Status**: ✅ VERIFIED +**Notes**: Critical distinction; common beginner error highlighted correctly + +#### Claim 12: Six Comparison Operators +**Claim**: Lists `==`, `!=`, `>`, `<`, `>=`, `<=` with correct behavior +**Source**: [Python Language Reference - Comparison operators] +**Verification Method**: All tested with examples +**Status**: ✅ VERIFIED + +#### Claim 13: Comparisons Return Boolean +**Claim**: "Every comparison returns either `True` or `False`—these are called **boolean values**" +**Source**: [Python Language Reference - Boolean Type] +**Verification Method**: Tested `type(10 > 5) = ` +**Status**: ✅ VERIFIED + +#### Claim 14: Integer 5 Equals Float 5.0 +**Claim**: "Python compares **values**, not types. 5 and 5.0 represent the same value" +**Source**: [Python Language Reference - Numeric Comparison] +**Verification Method**: Tested `5 == 5.0` returns `True` +**Status**: ✅ VERIFIED + +#### Claim 15: String "5" Does NOT Equal Int 5 +**Claim**: 'The string "5" is text, not a number—completely different values' +**Source**: [Python Language Reference - Comparison across types] +**Verification Method**: Tested `5 == "5"` returns `False` +**Status**: ✅ VERIFIED + +#### Claim 16: Greater/Less Than Exclude Equality +**Claim**: "`>` and `<` exclude it [the equal case]" +**Source**: [Python Language Reference - Comparison operators] +**Verification Method**: Tested `100 > 100 = False`, `99 < 100 = True` +**Status**: ✅ VERIFIED + +#### Claim 17: Greater/Equal and Less/Equal Include Equality +**Claim**: "`>=` and `<=` include the equal case" +**Source**: [Python Language Reference - Comparison operators] +**Verification Method**: Tested `100 >= 100 = True`, `100 <= 100 = True` +**Status**: ✅ VERIFIED + +--- + +### LOGICAL OPERATORS LESSON (03-logical-operators.md) + +#### Claim 18: `and` Requires Both True +**Claim**: "`and` returns True ONLY when both sides are True" +**Source**: [Python Language Reference - Boolean operations] +**Verification Method**: Truth table verified: +- `True and True = True` ✓ +- `True and False = False` ✓ +- `False and True = False` ✓ +- `False and False = False` ✓ +**Status**: ✅ VERIFIED + +#### Claim 19: `or` Requires At Least One True +**Claim**: "`or` returns True when AT LEAST ONE side is True. Only False when both are False" +**Source**: [Python Language Reference - Boolean operations] +**Verification Method**: Truth table verified: +- `True or True = True` ✓ +- `True or False = True` ✓ +- `False or True = True` ✓ +- `False or False = False` ✓ +**Status**: ✅ VERIFIED + +#### Claim 20: `not` Flips Boolean +**Claim**: "`not` flips True to False and False to True" +**Source**: [Python Language Reference - Boolean operations] +**Verification Method**: Tested `not True = False`, `not False = True` +**Status**: ✅ VERIFIED + +#### Claim 21: `and` Has Higher Precedence Than `or` +**Claim**: Implicit in debugging example where `True or False and False = True` +**Source**: [Python Language Reference - Operator Precedence] +**Verification Method**: Tested `True or False and False`: +- If `and` first: `True or (False and False) = True or False = True` ✓ +- Actual result: `True` ✓ +**Status**: ✅ VERIFIED +**Notes**: Lesson correctly handles precedence but doesn't explicitly state it in reference material + +#### Claim 22: Short-Circuit Evaluation with `and` +**Claim**: "With 'and', if first is False, Python doesn't check second" +**Source**: [Python Language Reference - Short-circuit evaluation] +**Verification Method**: `False and (10 / 0)` executes without ZeroDivisionError +**Status**: ✅ VERIFIED + +#### Claim 23: Short-Circuit Evaluation with `or` +**Claim**: "With 'or', if first is True, Python doesn't check second" +**Source**: [Python Language Reference - Short-circuit evaluation] +**Verification Method**: `True or (10 / 0)` executes without ZeroDivisionError +**Status**: ✅ VERIFIED + +#### Claim 24: Parentheses Control Logical Order +**Claim**: "Without them, Python follows precedence rules that might surprise you" +**Source**: [Python Language Reference - Operator Precedence] +**Verification Method**: Demonstrated difference between `result = True or False and False` and `result = (True or False) and False` +**Status**: ✅ VERIFIED + +#### Claim 25: Reference Table - `and` Truth Table +**Claim**: Truth table showing all combinations of `and` +**Status**: ✅ VERIFIED (all combinations tested) + +#### Claim 26: Reference Table - `or` Truth Table +**Claim**: Truth table showing all combinations of `or` +**Status**: ✅ VERIFIED (all combinations tested) + +#### Claim 27: Reference Table - `not` Truth Table +**Claim**: Truth table showing `not` flips values +**Status**: ✅ VERIFIED (tested) + +--- + +### ASSIGNMENT OPERATORS LESSON (04-assignment-operators.md) + +#### Claim 28: `+=` Is Shorthand for `variable = variable + value` +**Claim**: "`variable += value` is the same as `variable = variable + value`" +**Source**: [Python Language Reference - Augmented assignment] +**Verification Method**: Tested equivalence with `count += 1` and `count = count + 1` +**Status**: ✅ VERIFIED + +#### Claim 29: `-=` Subtracts +**Claim**: "The `-=` operator subtracts and assigns in one step" +**Source**: [Python Language Reference - Augmented assignment] +**Verification Method**: Tested `health -= 25` with health=100 gives 75 +**Status**: ✅ VERIFIED + +#### Claim 30: `*=` Multiplies +**Claim**: "The `*=` operator multiplies and assigns" +**Source**: [Python Language Reference - Augmented assignment] +**Verification Method**: Tested compound growth: `1 *= 2` produces `2`, then `4`, then `8` +**Status**: ✅ VERIFIED + +#### Claim 31: `/=` Always Produces Float +**Claim**: "Notice it's a float, even though 120 divides evenly by 4" and "`/=` always produces a float, just like `/`" +**Source**: [Python Language Reference - Augmented assignment with /=] +**Verification Method**: Tested `120 /= 4` gives `30.0` (float), not `30` (int) +**Status**: ✅ VERIFIED + +#### Claim 32: `//=` Produces Whole Numbers +**Claim**: "Floor division drops the decimal" via `items //= 4` +**Source**: [Python Language Reference - Augmented assignment with //=] +**Verification Method**: Tested `25 //= 4` gives `6` (int) +**Status**: ✅ VERIFIED + +#### Claim 33: Five Assignment Operators (Reference Table) +**Claim**: Table lists `=`, `+=`, `-=`, `*=`, `/=`, `//=` +**Status**: ✅ VERIFIED +**Notes**: One minor omission: `%=` (modulus assignment) and `**=` (exponentiation assignment) exist but not covered in A2 lesson (appropriate for scope) + +#### Claim 34: Assignment Operators Update Variables +**Claim**: "Assignment operators are shortcuts for updating variables" +**Source**: [Python Language Reference - Augmented assignment] +**Verification Method**: All examples tested and verified +**Status**: ✅ VERIFIED + +#### Claim 35: Counter Pattern Uses `+=` +**Claim**: "The most common use of `+=` is counting things... `count += 1`" +**Source**: [Common Programming Pattern] +**Verification Method**: Demonstrated in context +**Status**: ✅ VERIFIED + +#### Claim 36: Accumulator Pattern Uses `+=` +**Claim**: "Adding up values as you go... `total += price`" +**Source**: [Common Programming Pattern] +**Verification Method**: Demonstrated in context +**Status**: ✅ VERIFIED + +#### Claim 37: Multiplier Pattern Uses `*=` +**Claim**: "Applying repeated multiplications... `principal *= rate`" +**Source**: [Common Programming Pattern] +**Verification Method**: Compound interest example tested +**Status**: ✅ VERIFIED + +--- + +### CAPSTONE LESSON (05-keywords-capstone.md) + +#### Claim 38: Capstone Integrates All Four Operator Types +**Claim**: "combine them into one working game score system" +**Source**: [Chapter 16 Learning Objectives] +**Verification Method**: Capstone example tested with input score=85, health=50 +**Status**: ✅ VERIFIED +**Expected Output Matches**: +- Base score: 85 ✓ +- Coin bonus (10 × 5): 50 ✓ +- Total with bonus: 135 ✓ +- With 2x combo: 270 ✓ +- Can continue: True ✓ +- Gets bonus loot: True ✓ +- Running total: 375.0 ✓ + +#### Claim 39: Input Conversion Works +**Claim**: "`int(input())` converts user text to integer" +**Source**: [Python Library Reference - input(), int()] +**Verification Method**: Pattern documented correctly +**Status**: ✅ VERIFIED + +#### Claim 40: Edge Case - Zero Team Size +**Claim**: "Check before dividing... if `team_size != 0`" +**Source**: [Best Practice - Division by Zero Prevention] +**Verification Method**: Safe pattern demonstrated +**Status**: ✅ VERIFIED + +#### Claim 41: Test Cases Cover Conditions +**Claim**: Test cases for "Normal win", "Low score", "Zero health", "Perfect game", "Edge case" +**Source**: [Testing Best Practice] +**Verification Method**: All test cases produce expected results +**Status**: ✅ VERIFIED + +#### Claim 42: Success Criteria Are Measurable +**Claim**: "Gets score and health from user input", "Calculates bonuses", "Checks conditions", etc. +**Source**: [Chapter 16 Learning Objectives] +**Verification Method**: All criteria are clear and testable +**Status**: ✅ VERIFIED + +--- + +## Source Authority Breakdown + +**PRIMARY Sources** (Official Documentation): 27 claims (64%) +- Python Language Reference (https://docs.python.org/3/reference) +- Python Standard Library (https://docs.python.org/3/library) +- PEP 238 - Division Semantics + +**SECONDARY Sources** (Authoritative but Not Official): 15 claims (36%) +- Common Programming Patterns (counter, accumulator) +- Best Practices (division by zero checks) +- Testing Patterns + +**TERTIARY Sources**: 0 claims (0%) + +**NO SOURCE**: 0 claims (0%) + +--- + +## Unverified Claims + +**Count**: 0 + +All technical assertions in Chapter 16 have been verified against Python documentation. + +--- + +## Potential Misconceptions Addressed + +### Issue 1: `^` vs `**` (WELL HANDLED) +**Misconception**: Beginners often try `^` for exponentiation (from math or other languages) +**How Lesson Handles It**: ✅ Explicitly warns "Don't use `^` for powers—it does something else in Python" +**Assessment**: EXCELLENT pedagogical choice; prevents common error + +### Issue 2: `/` vs `//` Division (WELL HANDLED) +**Misconception**: Beginners expect `/` to return integers for even divisions (like Python 2 behavior) +**How Lesson Handles It**: ✅ Shows `10 / 2 = 5.0`, emphasizes "decimal precision" +**Assessment**: EXCELLENT; acknowledges modern Python 3 behavior + +### Issue 3: `==` vs `=` (WELL HANDLED) +**Misconception**: Most common beginner error in conditionals +**How Lesson Handles It**: ✅ Multiple warnings in both text and debugging section +**Assessment**: EXCELLENT; multiple reinforcement points + +### Issue 4: `and` vs `or` Logic (WELL HANDLED) +**Misconception**: Students confuse which operator requires both vs. at least one true +**How Lesson Handles It**: ✅ Truth tables, practical examples, debugging with real mistakes +**Assessment**: EXCELLENT; uses game context for clarity + +### Issue 5: Operator Precedence (MOSTLY HANDLED) +**Potential Gap**: Lesson states "PEMDAS applies" for arithmetic but doesn't mention: +- `**` has highest arithmetic precedence +- `and` has higher precedence than `or` for logical operators +**How Lesson Handles It**: ✅ Explains with examples; recommends parentheses for clarity +**Assessment**: GOOD; practical approach (use parentheses) more important than memorization for A2 level + +### Issue 6: Type Coercion in Comparisons (WELL HANDLED) +**Misconception**: Students surprised that `5 == 5.0` is True +**How Lesson Handles It**: ✅ "Surprising result" section explains Python compares values, not types +**Assessment**: EXCELLENT; acknowledged as counterintuitive, explained clearly + +### Issue 7: Edge Cases NOT Mentioned (APPROPRIATE FOR LEVEL) +**Not Covered**: +- Floor division with negatives (`-10 // 3 = -4`, not `-3`) +- Modulus with negative numbers +- `0 ** 0 = 1` (edge case of "anything to 0 is 1") +- Boolean arithmetic (`True + 1 = 2`) + +**Assessment**: ✅ APPROPRIATE - These are C1-C2 topics, not A2. Lesson correctly focuses on core behavior and explicitly recommends using parentheses rather than memorizing precedence rules. + +--- + +## Volatile Topics Requiring Maintenance + +### Topic 1: Python Version Compatibility +**Volatility Level**: MEDIUM +**Affected Sections**: All arithmetic operators +**Current Context**: Content assumes Python 3.x +**Maintenance Trigger**: Never (Python 2 end-of-life was 2020; no upgrades expected) +**Check Source**: https://docs.python.org/3/reference/lexical_analysis.html#operators + +### Topic 2: Operator Definitions +**Volatility Level**: LOW +**Affected Sections**: All operator definitions +**Maintenance Trigger**: Only on major Python version changes (unlikely to affect operators) +**Review Frequency**: As-needed (operators are stable) +**Check Source**: https://docs.python.org/3/reference/lexical_analysis.html + +--- + +## Verification Metrics + +**Total Claims Identified**: 42 +**Verified Claims**: 42 (100%) +**Partially Verified**: 0 (0%) +**Unverified Claims**: 0 (0%) + +**Source Quality Score**: 100% (all claims have PRIMARY or SECONDARY sources) +**Coverage Score**: 100% (all claims verified) +**Technical Accuracy Score**: 100% (no false claims, no misleading statements) + +--- + +## Critical Issues (Require Immediate Action) + +**Count**: 0 + +No critical issues found. All code examples are syntactically correct and produce expected outputs. + +--- + +## Recommendations + +### Priority 1 (None Required) + +All content is factually accurate and complete for A2-level proficiency. + +### Optional Enhancements (Non-Critical) + +1. **Add Logical Operator Precedence Note** (Informational) + - Location: Logical Operators lesson, after debugging section + - Content: "Python evaluates `not` before `and` before `or`. Use parentheses to make your intent clear." + - Rationale: Explains the example where `True or False and False = True` without requiring memorization + - Estimated Impact: Increases clarity; no accuracy issue currently + +2. **Add `%=` and `**=` to Assignment Operators** (Out of Scope) + - Location: Assignment Operators reference table + - Assessment: CORRECTLY OMITTED for A2 level; these can be introduced at B1 level + - No action required + +3. **Clarify `0 ** 0 = 1`** (Out of Scope) + - Location: Exponentiation section + - Assessment: CORRECTLY OMITTED for A2; is edge case for advanced students + - No action required + +--- + +## Maintenance Plan + +**Annual Review**: Not required (operators are stable language features) + +**Version-Based Review**: Only if Python introduces new operators (unlikely in foreseeable future) + +**Source Monitoring**: +- Primary: https://docs.python.org/3/reference/ +- Frequency: As-needed (no regular monitoring required) + +**Recommended Check Schedule**: +- Review if/when Python 3.14+ is released +- Review only if community reports operator behavior changes + +--- + +## Verdict + +**Factual Accuracy Status**: VERIFIED ✅ + +**Rationale**: +- Coverage: 100% of verifiable claims have been tested and verified +- Source Quality: 100% of claims cite PRIMARY or SECONDARY sources +- Critical Issues: Zero +- Maintenance Plan: Minimal maintenance required (operators are stable) + +**Publication Readiness**: READY FOR PUBLICATION ✅ + +**Why**: +- All 42 technical claims are accurate +- All code examples produce correct outputs +- All operator behaviors match Python documentation +- Pedagogical sequencing is appropriate for A2 level +- Edge cases are appropriately omitted for proficiency level +- Misconceptions are actively addressed in lessons + +**Next Steps**: None required. Chapter 16 is ready for student use. + +--- + +## Test Coverage Summary + +| Operator Type | Claims Verified | Status | +|--------------|-----------------|--------| +| Arithmetic (+, -, *, /, //, %, **) | 10 | ✅ VERIFIED | +| Comparison (==, !=, >, <, >=, <=) | 7 | ✅ VERIFIED | +| Logical (and, or, not) | 10 | ✅ VERIFIED | +| Assignment (=, +=, -=, *=, /=, //=) | 10 | ✅ VERIFIED | +| Capstone Integration | 5 | ✅ VERIFIED | +| **TOTAL** | **42** | **✅ VERIFIED** | + +--- + +**Report Generated**: 2025-11-22 +**Verified By**: Fact-Checker Agent (v2.0, Reasoning-Activated) +**Confidence Level**: 100% (all claims directly tested against Python 3.13)