LOGIC
UNLOCKED
Mastering Control Flow, Loops, Functional Decomposition, and the mind-bending mechanics of RECURSION. Includes hands-on workouts and interactive project builds.
WHAT WE'LL COVER
06 MODULES · 04 QUIZZES · 03 PROJECTS · 200 PTS
USE ← → ARROW KEYS OR THE BUTTONS BELOW TO NAVIGATE
DECISION MAKING: IF-ELSE & NESTED LOGIC
Programs need to make choices based on data. Python uses
if,
elif, and
else keywords to construct
decision paths.
Short-Circuit Evaluation:
• In A and B, if A is
False, B is never evaluated.
• In A or B, if A is
True, B is skipped immediately.
age = 19 has_license = True if age >= 18: # Nested condition inside primary block if has_license: print("Eligible to drive vehicle.") else: print("Age valid, but driver's license required!") else: print("Underage. Driving restricted.")
DECISION LOGIC CHECK
What will be the output of the following code snippet?
x = 10
if x > 15:
print("A")
elif x > 5 and x < 12:
print("B")
else:
print("C")
LOOPS & REPETITION MECHANICS
Loops allow executing a block of code repeatedly until a condition changes or a sequence is exhausted.
Best for iterating over known sequences or predefined range limits.
for i in range(1, 5, 1):
range(start, stop, step)
Executes indefinitely as long as condition evaluates to True.
while count < 5:
Requires manual state updates!
• break: Immediately
terminates loop execution.
• continue: Skips current
iteration & moves to next.
• pass: Placeholder statement
(does nothing).
rows = 4 for i in range(1, rows + 1): for j in range(i): print("*", end=" ") print() # Newline after inner loop completion
*
* *
* * *
* * * *
RANGE & LOOP PREDICTION
What is printed by:
list(range(2, 10, 3))?
FUNCTIONS & VARIABLE SCOPE
Functions are reusable blocks of code defined using
def. They reduce
duplication and build modular architecture.
• Parameters vs Arguments: Placeholders in definition vs actual values passed during invocation.
• Return Value: Sends data back to caller.
Without an explicit return, functions yield
None.
• Scope Rules (LEGB): Local -> Enclosing -> Global -> Built-in.
*args accepts dynamic
positional arguments as a tuple.**kwargs accepts dynamic
keyword arguments as a dictionary.
tax_rate = 0.18 # Global Variable def calculate_total(price, discount=0): # Local variable calculation final_price = (price - discount) * (1 + tax_rate) return round(final_price, 2) total = calculate_total(100, discount=10) print(f"Final Amount: ${total}")
FUNCTION SCOPE
What happens when attempting to print a local variable outside its function?
RECURSION: SELF-REFERENTIAL LOGIC
Recursion is a technique where a function calls itself to break down a problem into smaller instances.
RECURSION IN PRACTICE
def factorial(n): # Base Case if n == 1: return 1 # Recursive Step return n * factorial(n - 1)
def fibonacci(n): # Base Cases if n <= 0: return 0 if n == 1: return 1 # Double Recursive Step return fibonacci(n - 1) + fibonacci(n - 2)
What error occurs if a recursive function lacks a base case?
PROBLEMS WORKOUT & ALGORITHMS
Write an algorithm to determine if a given integer n > 1 is prime.
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True
Check if a string reads the same backwards using slice
notation [::-1].
def is_palindrome(s): cleaned = "".join(char.lower() for char in s if char.isalnum()) return cleaned == cleaned[::-1]
DAY 2 MINI-PROJECT BUILD SESSIONS
Interactive Python Calculator Logic
Executes arithmetic operations using modular functional dispatching.
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): return a / b if b != 0 else "Error: Division by Zero" operations = {'+': add, '-': subtract, '*': multiply, '/': divide} num1 = float(input("First number: ")) op = input("Operator (+,-,*,/): ") num2 = float(input("Second number: ")) if op in operations: result = operations[op](num1, num2) print(f"Result: {result}")
Number Guessing Game (1 - 100)
Uses random module and while loop iteration.
Guess secret number between 1 and 100:
import random secret = random.randint(1, 100) attempts = 0 while True: guess = int(input("Guess number (1-100): ")) attempts += 1 if guess < secret: print("TOO LOW! Try higher.") elif guess > secret: print("TOO HIGH! Try lower.") else: print(f"CORRECT! Solved in {attempts} tries.") break
In-Memory Student Records System
Manipulate student data structures via function calls.
• Ananya - Grade: A+
database = [] def add_student(name, grade): student = {"name": name, "grade": grade} database.append(student) print(f"Record saved for {name}.") def view_students(): for idx, s in enumerate(database, 1): print(f"{idx}. {s['name']} - Grade: {s['grade']}")
KEEP CODING
You've covered decisions, loops, functions and recursion. Now build the three projects, solve the workout problems, and push your code to GitHub.