1 / 26
Python Programming · Grade 8 · Chapter 3

Python Refresher & Logic Mastery

Revisiting variables, data types, conditional branching, and loop control structures to build rock-solid Python foundations.

Historical Debugging Tale

The $370 Million Type Error

In 1996, the Ariane 5 rocket exploded 37 seconds after launch because software attempted to store a 64-bit floating-point number into a 16-bit integer variable, causing an arithmetic overflow crash.

Lesson: Data types, variable assignments, and boundary checks matter in every program!
Lesson Objectives

What We Will Master Today

Prior Knowledge Connection

Grade 7 Review vs. Grade 8 Rigor

Grade 7 Foundations

Basic print() statements, simple user input, and single if checks.

Grade 8 Target

Robust error validation, type safety, nested logic guards, and algorithm optimization.

Core Concept 1

Variables & Dynamic Typing

Variables in Python act as labeled tags pointing to objects stored in computer RAM.

# Variable creation and reassignment score = 100 # int type player_name = "Sara" # str type is_active = True # bool type # Dynamic re-binding score = score + 15.5 # converted to float automatically print(type(score)) # <class 'float'>
Core Data Types

Understanding Core Python Types

Integer & Float

age = 14 (Whole numbers)
gpa = 3.92 (Decimals)

String & Boolean

role = "Admin" (Text sequences)
is_verified = True (Truth values)

Core Concept 2

Type Casting & Input Protection

Python's input() function ALWAYS returns text (str). Explicit casting is required for calculations.

Bug: Missing Type Casting

age = input("Age: ") # "14" print(age + 1) # TypeError!

Correct: Explicit Casting

age = int(input("Age: ")) print(age + 1) # Prints 15
Core Concept 3

Boolean Operators & Truth Tables

Combine multiple boolean conditions using and, or, and not.

AND Operator

Returns True ONLY if both conditions are true.

OR Operator

Returns True if at least one condition is true.

NOT Operator

Inverts boolean state: not True becomes False.

Control Flow

Conditional Branching: `if / elif / else`

age = 14 has_parent_permission = True if age >= 18: print("Access Granted: Full Ticket") elif age >= 13 and has_parent_permission: print("Access Granted: Youth Ticket") else: print("Access Denied")
Loop Structures

Definite Iteration with `for` Loops

Use for loops when repeating code a known number of times or iterating over sequence items.

# Loop through range(start, stop, step) for i in range(1, 6): print(f"Count step: {i}") # Loop through string sequence for char in "PYTHON": print(char.lower())
Loop Structures

Indefinite Iteration with `while` Loops

Use while loops when repeating code until a dynamic condition changes. Always ensure a sentinel variable stops the loop!

attempts = 0 max_attempts = 3 while attempts < max_attempts: pwd = input("Enter passcode: ") if pwd == "cyber8": print("Unlocked!") break attempts += 1 print(f"Wrong! Left: {max_attempts - attempts}")
Loop Flowchart

`break` vs. `continue` Statements

break Keyword

Exits the loop immediately and jumps to code after the loop block.

continue Keyword

Skips the rest of the current iteration and jumps back to the top condition check.

Modern Formatting

String Formatting with F-Strings

Python 3 f-strings allow embedding expressions directly inside string literals cleanly.

item = "Microcontroller" price = 24.99 qty = 3 # Modern Python f-string syntax summary = f"Order: {qty}x {item} | Total: ${price * qty:.2f}" print(summary) # Order: 3x Microcontroller | Total: $74.97
Scenario Analysis

Building a Login Gateway System

LOGIC DESIGN

Design the control flow for a banking app login system. System locks account after 3 failed attempts, checks if account is active, and sends 2FA code if credentials pass.

Brainstorm: Draw the nested if/else and while loop structure on paper.
Spot the Mistake

Debugging 3 Common Python Errors

# Bug 1: IndentationError def check_number(x): print(x) # Missing tab/indent # Bug 2: SyntaxError (= vs ==) if score = 100: # Should be == print("Perfect!") # Bug 3: Infinite Loop count = 1 while count <= 5: print(count) # Missing count += 1!
Guided Practice

Interactive Guessing Game Algorithm

Analyze the complete code structure for a high-low guessing game:

import random target = random.randint(1, 20) guesses = 0 while True: guess = int(input("Guess (1-20): ")) guesses += 1 if guess == target: print(f"Correct in {guesses} tries!") break elif guess < target: print("Too low!") else: print("Too high!")
Hands-on Challenge

Build a Grade Classifier

Write code that prompts for a score (0-100), validates input, and outputs the letter grade:

Check Your Understanding

What is the output of `type(5 / 2)` in Python 3?

A<class 'int'>
B<class 'float'>
C<class 'str'>
D<class 'bool'>
Click to reveal answer
Check Your Understanding

What does `range(2, 10, 3)` generate in a `for` loop?

A2, 3, 4, 5, 6, 7, 8, 9, 10
B3, 6, 9
C2, 5, 8
D2, 10, 3
Click to reveal answer
Check Your Understanding

Evaluate: `(True or False) and not (False or True)`

ATrue
BFalse
CNone
DSyntaxError
Click to reveal answer
Check Your Understanding

Which keyword skips the remainder of the current loop iteration?

Abreak
Bcontinue
Cexit
Dpass
Click to reveal answer
Code Readability & PEP 8

Writing Professional Python Code

PEP 8 is Python's official style guide. Why do professional developers prioritize clean code layout and self-documenting variable names?

Discussion: Compare x = a * 0.15 vs tax_amount = total_price * TAX_RATE.
Application Challenge

Build a Command-Line Menu Shell

Construct a interactive terminal menu shell using a while True loop and match/case or if/elif:

# Menu template print("1. Start Game | 2. View High Scores | 3. Exit")
Chapter Summary

Python Fundamentals Mastery

Exit Ticket

Quick Logic Challenge

1. Write the single line of Python code to prompt a user for an integer age and store it in variable user_age.
2. What happens if a user types "fourteen" into your code? How can we fix it?
Looking Ahead

Next Chapter: Functions & Scope

With core logic refreshed, we are ready to organize our code into reusable functions and explore local vs. global scope!