0% found this document useful (0 votes)
29 views68 pages

Python Programming Course Slides

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views68 pages

Python Programming Course Slides

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Presentation Data

You've refined the course outline wonderfully! It's very well-structured for high school students.

Here's the data for 14 presentation slides, covering the core concepts from your updated
outline. Each slide will include explanations, syntax, and a runnable code example.

Python Programming Course: Presentation Slide Data

General Instructions for Presenter:

 Keep it interactive: Encourage questions, ask students to predict output.

 Live coding: Supplement these slides with live coding demonstrations in an IDE.

 Hands-on: Emphasize the "Interactive Session" challenges as their primary learning


method.

 Simplify: Use analogies familiar to high school students (recipes for algorithms, storage
boxes for variables).

Day 1:
Slide 1: Welcome to Python Programming!

 Title: Welcome to Python Programming! Your Journey Begins Here

 Image Suggestion: A vibrant Python logo, or a graphic showing a programmer creating


something cool (robot, game, website).

 Content:

o What is Programming?

 Think of it like giving a very precise set of instructions to a computer to


perform a task.

 It's how we build apps, games, websites, and even control robots!

o What is an Algorithm?

 A step-by-step recipe or a clear set of instructions to solve a problem.


Before you write code, you design an algorithm!

o Why Python?
 Python is known for being easy to read and write, like natural language.

 It's used everywhere: building websites, analyzing data, making AI, and
even games!

 Key Takeaway: Programming is problem-solving with computers, and Python is a


powerful and friendly language to start with.

Slide 2: Getting Started: Your First Steps with Python

 Title: Setting Up Your Python Workspace

 Content:

o Setting up the Environment: We need a place for Python to run. We'll install
Python on your computer and set up a "virtual environment" – think of it as a
clean, isolated workspace for each project.

o Comments: Notes in your code that Python ignores. They are crucial for humans
to understand what your code does!

 Syntax: # This is a single-line comment or """This is a multi-line


comment"""

o Variables: Imagine a variable as a labeled box in your computer's memory where


you can store different types of information.

 Syntax: variable_name = value

 Code Example:

Python

# This is my first Python program!

# Storing my name in a variable

my_name = "Alice"

my_age = 15 # This is an integer

greeting = "Hello, " + my_name + "!" # Combining strings

print(greeting)
print("I am", my_age, "years old.")

 Explanation for Students: We'll guide you through installing Python and setting up your
first project space. Comments help you and others understand your code, and variables
are like containers for information your program uses.

Slide 3: Data Types: The Kinds of Information Python Handles

 Title: Understanding Data: Numbers, Text, and More!

 Content:

o Fundamental Data Types: Python handles different kinds of data. Knowing them
helps you use them correctly.

 Integers (int): Whole numbers (e.g., 5, -10, 0).

 Floating-Point Numbers (float): Numbers with decimals (e.g., 3.14, -0.5).

 Strings (str): Text, enclosed in quotes (e.g., "Hello", 'Python').

 Booleans (bool): Represents True or False. Used for logic.

o Basic Input and Output:

 print() displays information to the user.

 input() gets information from the user.

 Code Example:

Python

user_name = input("What's your name? ")

birth_year_str = input("What year were you born? ")

# Convert string input to integer

current_year = 2025

birth_year = int(birth_year_str)

age = current_year - birth_year


print(f"Hello, {user_name}! You are approximately {age} years old.")

is_adult = (age >= 18) # This will be True or False (boolean)

print(f"Are you an adult? {is_adult}")

 Explanation for Students: Python understands different types of information like whole
numbers, decimals, and text. We use print() to show things and input() to let the user
type something in. We often need to convert input from text to numbers to do
calculations.

Slide 4: Operators: Making Python Do the Math & Logic!

 Title: Operators: Your Tools for Calculations and Decisions

 Content:

o Arithmetic Operators: Perform mathematical calculations.

 + (addition), - (subtraction), * (multiplication), / (division)

 % (modulo - remainder), ** (exponentiation), // (floor division - whole


number result)

o Comparison Operators: Compare values, resulting in True or False.

 == (equal to), != (not equal to)

 > (greater than), < (less than), >= (greater than or equal to), <= (less than
or equal to)

o Logical Operators: Combine boolean expressions.

 and (both true), or (at least one true), not (reverses truth)

o Assignment Operators: Shorthand for operations and assignment (e.g., x += 5 is x


= x + 5).

o Operator Precedence: The order in which operations are performed (like


PEMDAS in math).

Parentheses (): Expressions enclosed in parentheses are evaluated first, overriding other
precedence rules.
Exponentiation `: `**: Raising a number to a power.

Unary operators +x, -x, ~x: Unary plus, unary minus, and bitwise NOT.

Multiplication, Division, Modulo, Floor Division *, /, %, //: Standard arithmetic operations.

Addition and Subtraction +, -: Standard arithmetic operations.

Bitwise shifts <<, >>: Left and right bitwise shifts.

Bitwise AND &: Bitwise AND operation.

Bitwise XOR ^: Bitwise exclusive OR operation.

Bitwise OR |: Bitwise OR operation.

Comparisons, Identity, Membership ==, !=, <, >, <=, >=, is, is not, in, not in: Relational and
identity checks.

Logical NOT not: Logical negation.

Logical AND and: Logical conjunction.

Logical OR or: Logical disjunction.

Conditional expression x if y else z: Ternary operator.

Assignment operators =, +=, -=, etc. Assigning values to variables.

Lambda lambda: Defining anonymous functions.

 Code Example:

Python

celsius_temp = 25

fahrenheit_temp = (celsius_temp * 9/5) + 32

print(f"{celsius_temp}°C is {fahrenheit_temp}°F")

my_money = 100

exchange_rate = 280.50 # PKR per USD

pkr_amount = my_money * exchange_rate

print(f"${my_money} USD is {pkr_amount:.2f} PKR") # .2f for 2 decimal places


is_hot = (fahrenheit_temp > 80)

is_sunny = True

go_outside = is_hot and is_sunny # Logical AND

print(f"Is it hot AND sunny? {go_outside}")

 Explanation for Students: Operators are the symbols we use to do calculations, compare
things, and combine true/false statements. Just like in math, there's an order to how
Python solves these operations.

Day 2:
Slide 5: Control Flow: Making Decisions with If Conditions

 Title: Control Flow: Guiding Your Program's Decisions

 Content:

o if Statement: Executes a block of code only if a condition is True.

 Syntax:

Python

if condition:

# code to execute if condition is True

o if-elif-else: Allows for multiple possible conditions. The first True condition's
block executes.

 Syntax:

Python

if condition1:

# code if condition1 is True

elif condition2:

# code if condition2 is True

else:
# code if no conditions above are True

o match case (Python 3.10+): A newer way to handle multiple specific values or
patterns. Think of it like a more powerful if-elif-else for matching exact states.

 Syntax:

Python

match variable:

case value1:

# code for value1

case value2:

# code for value2

case _: # default case

# code if no match

o Ternary Operator (Conditional Expression): A compact way to write an if-else


statement on a single line for assigning a value.

 Syntax: value_if_true if condition else value_if_false

 Code Example:

Python

score = 85

if score >= 90:

grade = "A"

elif score >= 80:

grade = "B"

elif score >= 70:

grade = "C"

else:

grade = "F"

print(f"Score: {score}, Grade: {grade}")


# Using ternary operator

status = "Passed" if score >= 60 else "Failed"

print(f"You {status} the exam.")

# Using match case (if Python 3.10+)

day_number = 3

match day_number:

case 1:

day_name = "Monday"

case 2:

day_name = "Tuesday"

case 3:

day_name = "Wednesday"

case _:

day_name = "Unknown"

print(f"Day {day_number} is {day_name}")

 Explanation for Students: Control flow lets your program make choices. if statements
check conditions, elif and else provide alternatives. match case is great for specific
scenarios, and the ternary operator is a shortcut for simple choices.

Slide 6: Loops: Repeating Actions with While & For

 Title: Loops: Doing Things Over and Over (Efficiently!)

 Content:

o while Loop: Repeats a block of code as long as a condition is True. Useful when
you don't know how many times to repeat.

 Syntax:
Python

while condition:

# code to repeat

 break: Immediately exits the loop.

 continue: Skips the rest of the current loop iteration and goes to the next.

The break Statement

 Purpose: The break statement is used to immediately terminate the current loop.

o When Python encounters break, it completely exits the loop, and execution
continues with the first statement after the loop.

 Analogy: Imagine you're running laps around a track (while loop). Suddenly, the coach
blows a whistle (break!): you stop running immediately and go home, no matter how
many laps you had left.

Syntax:

Python

while condition:

# Code inside the loop

if special_condition:

break # Exit the loop immediately

# More code inside the loop

Code Example Snippet:

Python

# Problem: Search for a specific number in a sequence

secret_number = 7

current_number = 1

print("Searching for the secret number...")

while current_number <= 10:


print(f"Checking {current_number}...")

if current_number == secret_number:

print(f"Found the secret number: {secret_number}!")

break # Exit the loop as soon as we find it

current_number += 1

print("Loop finished (or broken out of).")

# Output:

# Searching for the secret number...

# Checking 1...

# Checking 2...

# Checking 3...

# Checking 4...

# Checking 5...

# Checking 6...

# Checking 7...

# Found the secret number: 7!

# Loop finished (or broken out of).

Explanation for Students: In this example, our while loop is designed to check numbers from 1
to 10. But because we use break, as soon as current_number becomes 7 (our secret_number),
the break statement kicks us out of the loop immediately. We don't check numbers 8, 9, or 10.

2. The continue Statement

 Purpose: The continue statement is used to skip the rest of the current iteration of the
loop and move directly to the next iteration (checking the loop condition again).
o When Python encounters continue, it stops executing the current block of code
within the loop and jumps back to the beginning of the loop to re-evaluate the
condition for the next cycle.

 Analogy: You're still running laps (while loop). You come across a puddle (continue!).
Instead of stopping, you just jump over the puddle and immediately continue running
the next part of your current lap, and then the next lap.

Syntax:

Python

while condition:

# Code before continue

if special_condition:

continue # Skip remaining code in this iteration

# Code after continue (this will be skipped if special_condition is True)

Code Example Snippet:

Python

# Problem: Print even numbers from 1 to 10, skipping odd numbers

count = 0

print("Printing even numbers from 1 to 10:")

while count < 10:

count += 1 # Increment first

if count % 2 != 0: # If the number is ODD

continue # Skip the print statement for odd numbers

print(f"Even number found: {count}")

print("Loop finished.")
# Output:

# Printing even numbers from 1 to 10:

# Even number found: 2

# Even number found: 4

# Even number found: 6

# Even number found: 8

# Even number found: 10

# Loop finished.

o for Loop: Iterates over items in a sequence (like a list, string, or range of
numbers). Useful when you know how many times to repeat or have a collection
of items.

 Syntax:

Python

for item in sequence:

# code to execute for each item

 range() function: Generates a sequence of numbers (e.g., range(5) gives 0,


1, 2, 3, 4).

o Nested Loops: A loop inside another loop, useful for rows and columns, or
patterns.

 Code Example:

Python

count = 0

while count < 3:

print("While loop iteration:", count)

count += 1
print("\n")

for i in range(5): # Iterates from 0 to 4

if i == 2:

continue # Skip 2

if i == 4:

break # Stop at 4

print("For loop iteration:", i)

print("\nPrinting a square:")

for row in range(3):

for col in range(3):

print("*", end=" ") # end=" " keeps on same line

print() # New line after each row

 Explanation for Students: Loops let your program repeat tasks without writing the same
code many times. while loops keep going as long as a condition is true, and for loops go
through each item in a collection or a range of numbers. You can even put loops inside
other loops for complex patterns!

Slide 7: Functions: Organizing Your Code for Reusability

 Title: Functions: Building Blocks for Reusable Code

 Content:

o Why Functions?

 Reusability: Write code once, use it many times.

 Modularity: Break down complex problems into smaller, manageable


pieces.
 Readability: Makes your code easier to understand and debug.

o Defining Functions: Use the def keyword.

 Syntax:

Python

def function_name(parameter1, parameter2=default_value):

# code inside the function

return result # Optional: sends a value back

o Calling Functions: Executing the code inside a function.

 Syntax: function_name(argument1, argument2)

o Arguments vs. Parameters: Parameters are placeholders in the definition,


arguments are the actual values passed when calling.

o Default Parameter Values: Provide a fallback if an argument isn't provided.

o Scope of Variables:

 Local: Defined inside a function, only accessible within that function.

 Global: Defined outside any function, accessible everywhere (use


sparingly!).

 Code Example:

Python

def calculate_gpa(grades_list):

total_points = sum(grades_list)

num_courses = len(grades_list)

gpa = total_points / num_courses

return gpa

def greet_user(name="Guest"): # Default parameter

print(f"Hello, {name}! Welcome to the program.")


# Calling functions

student_grades = [4.0, 3.5, 3.8, 3.0]

my_gpa = calculate_gpa(student_grades)

print(f"Your GPA is: {my_gpa:.2f}")

greet_user("Sarah")

greet_user() # Uses default "Guest"

 Explanation for Students: Functions are like mini-programs within your main program.
They help you organize your code, prevent repeating yourself, and make complex tasks
easier to manage. You give them inputs (arguments), and they can give you outputs
(return values).

1. "Countdown Timer" Function

o Description: Write a function called countdown(start_number). This function


should take an integer start_number as input. Using a while loop, the function
should print numbers from start_number down to 1, and then print "Go!".

o Concepts Reinforced: Functions (def, parameters), while loop, decrementing


counter.

o Example Output:

Python

countdown(5)

# Expected Output:

#5

#4

#3

#2

#1

# Go!

2. "Sum of Multiples" Function


o Description: Create a function named sum_multiples(limit, factor). This function
should calculate the sum of all numbers between 1 (inclusive) and limit
(exclusive) that are perfect multiples of factor. Use a for loop and the modulo
operator (%).

o Concepts Reinforced: Functions (def, parameters, return), for loop, range(),


modulo operator (%), conditional (if).

o Example Output:

Python

print(sum_multiples(10, 3))

# Expected Output: 18 (3 + 6 + 9)

print(sum_multiples(15, 5))

# Expected Output: 30 (5 + 10 + 15)

3. "Validate Positive Number" Function

o Description: Write a function called get_positive_number(). This function should


repeatedly ask the user to enter a positive number using a while loop. If the user
enters a non-positive number (zero or negative), it should print an error message
and ask again. The loop should only stop when a positive number is entered,
which the function then returns.

o Concepts Reinforced: Functions (def, return), while loop, input(), type conversion
(float() or int()), comparison operators, input validation.

o Example Output:

Python

num = get_positive_number()

print(f"You entered: {num}")

# Expected Interaction:

# Enter a positive number: -5

# Invalid input. Please enter a positive number.

# Enter a positive number: 0


# Invalid input. Please enter a positive number.

# Enter a positive number: 12.5

# You entered: 12.5

Write a Python program that uses nested for loops to print a 4x4 grid. The characters should
alternate between # and O like a chessboard.

Section 2: Nested Loops & Patterns

1. "Multiplication Table Printer" Function

o Description: Create a function print_multiplication_table(rows, cols). This


function should use nested for loops to print a multiplication table up to rows
and cols. For example, print_multiplication_table(3, 4) would print a table
showing products up to 3times4.

 Hint: You might need to use end="\t" in your print() statement for good
formatting, and print() without arguments to move to the next line after
each row.

o Concepts Reinforced: Functions (def, parameters), nested for loops, arithmetic


operations, print() formatting (end).

o Example Output:

Python

print_multiplication_table(3, 4)

# Expected Output:

#1 2 3 4

#2 4 6 8

#3 6 9 12

2. "Chessboard Pattern"

o Description: Write a function draw_chessboard(size). This function should print a


chessboard pattern of alternating '#' and ' ' (space) characters based on the given
size. Use nested loops.
o Concepts Reinforced: Functions (def, parameters), nested for loops, conditional
(if/else), modulo operator (%), print() formatting.

o Example Output:

Python

draw_chessboard(4)

# Expected Output:

###

# ##

###

# ##

o Hint: The pattern alternates based on whether the sum of the row and column
index is even or odd.

Section 3: Project-Style Challenges

1. "Simple Text Adventure Game"

o Description: Create a simple text adventure game using a while loop for the main
game loop and functions for different "rooms" or "scenarios."

 Start in a start_room() function.

 The main while loop continues as long as the player is not "dead" or has
not "won."

 Players should make choices (e.g., "go left", "open door") using input().

 Use if/elif/else within the functions to determine outcomes based on


choices.

 Include a way to break out of the main game loop (e.g., if the player types
"quit").

o Concepts Reinforced: while loop (main game loop), break, functions, input(),
conditional logic (if/elif/else), variables to track game state.

o Example Scenario (Highly Adaptable):

o def start_room():
o print("You are in a dark room. There is a door to your [left] and [right].")

o choice = input("What do you do? ").lower()

o if choice == "left":

o # Call another function for the left path

o return "You found a treasure chest! You win!"

o elif choice == "right":

o # Call another function for the right path

o return "A monster attacks! You lose!"

o else:

o return "You stumble around in the dark... nothing happens."

o # Main game loop concept

o game_active = True

o while game_active:

o result = start_room() # Call your starting room function

o print(result)

o if "win" in result or "lose" in result:

o game_active = False # End game condition

o play_again = input("Play again? (yes/no): ").lower()

o if play_again != "yes":

o game_active = False

o print("Thanks for playing!")

o Fun Element: Creative storytelling, decision-making.

2. "Basic Student Grade Manager"


o Description: Write a program that allows a teacher to enter student names and
their scores.

 Use a while loop to repeatedly ask for student names and scores until the
teacher types "done" for the name.

 Store the data (e.g., in a list of lists or a list of dictionaries).

 After data entry, create a function calculate_average_score(scores_list)


that takes a list of scores and returns their average.

 Create another function find_highest_score(scores_list) that returns the


highest score.

 Print a summary: total students, average score, and highest score.

o Concepts Reinforced: while loop, break, input(), type conversion (int()), lists (or
dictionaries), functions (with parameters and return values), for loop (for
calculation within functions), arithmetic operations, len(), max().

o Example Interaction:

o Enter student name (or 'done' to finish): Alice

o Enter Alice's score: 90

o Enter student name (or 'done' to finish): Bob

o Enter Bob's score: 75

o Enter student name (or 'done' to finish): Charlie

o Enter Charlie's score: 88

o Enter student name (or 'done' to finish): done

o --- Grade Summary ---

o Total students: 3

o Average score: 84.33

Highest score: 90
Simulate a very basic banking system for a single user.

 Start with an initial balance (e.g., $1000).

 Use a while loop to present a menu to the user:

1. Check Balance

2. Deposit

3. Withdraw

4. Exit

 Get the user's choice using input().

 Use if/elif/else (or match case if covered) to perform the selected action.

 For Deposit/Withdraw:

o Ask for the amount.

o Validate input (e.g., positive number, sufficient funds for withdrawal).

o Update the balance.

o Use continue to go back to the menu after an invalid input.

 Use break to exit the loop when the user chooses 'Exit'.

 (Optional function): Create functions for deposit(amount), withdraw(amount,


current_balance), and display_balance(balance).

Write a function print_numbered_pyramid(height). This function should print a pyramid where


each row contains its row number repeated. Use nested for loops.

Day 3:
Slide 8: String Manipulation: Playing with Text

 Title: String Manipulation: Your Text Toolbox

 Content:

o Strings are Immutable: Once created, you can't change individual characters in a
string. Any "modification" creates a new string.

o Indexing & Slicing: Access specific characters or parts of a string.

 my_string[index] (character at position)

 my_string[start:end] (substring)

o Common String Methods: Built-in tools for common text operations.

 len(): Get the length of a string.

 lower(), upper(), capitalize(), title(): Change case.

 strip(): Remove leading/trailing whitespace.

 find(), index(): Locate substrings.

 replace(): Substitute parts of a string.

 split(): Break a string into a list of words.

 join(): Combine a list of strings into one.

 Code Example:

Python

message = " Hello Python World! "

print(f"Original: '{message}'")

# Length and Case

print(f"Length: {len(message)}")

print(f"Uppercase: '{[Link]()}'")

# Stripping whitespace
trimmed_message = [Link]()

print(f"Trimmed: '{trimmed_message}'")

# Slicing and Replacing

print(f"Slice (0 to 5): '{trimmed_message[0:5]}'")

new_message = trimmed_message.replace("Python", "Awesome")

print(f"Replaced: '{new_message}'")

# Splitting and Joining

words = trimmed_message.split(" ")

print(f"Words: {words}")

joined_words = "-".join(words)

print(f"Joined with '-': {joined_words}")

# Password check concept

password = "MySecurePassword123"

is_long_enough = len(password) >= 8

has_uppercase = any([Link]() for char in password) # uses comprehension concept

has_digit = any([Link]() for char in password)

print(f"\nPassword check: Length OK? {is_long_enough}, Upper OK? {has_uppercase}, Digit OK?
{has_digit}")

 Explanation for Students: Strings are sequences of characters. You can grab parts of
them (slicing), check their length, change their case, and use powerful methods to
search, replace, and break them apart or put them together. Remember, when you
"change" a string, Python actually creates a brand new one!
 to represent characters that are difficult or impossible to type directly (like a newline), or
characters that would otherwise have special meaning in Python (like quotes).

 Emphasize that a backslash (\) indicates that the following character (or characters) should be
interpreted specially.

 \n: Newline (moves to the next line)

 print("Line 1\nLine 2")

 \t: Tab (inserts a horizontal tab space)

 print("Name:\tAlice")

 \' and \": Quotes within quotes (allows you to include the same type of quote that defines
the string)

 message = 'He said, "Hello!"' (no escape needed)

 message = "He said, \"Hello!\"" (escape needed if using double quotes inside double
quotes)

 message = 'It\'s a beautiful day.' (escape needed if using single quote inside single
quotes)

 \\: Literal Backslash (to print an actual backslash character)

 path = "C:\\Users\\Python"

Day 4:
Slide 9: Lists: Your Ordered Collections

 Title: Lists: Flexible Ordered Collections of Items

 Content:

o What are Lists? An ordered, changeable collection of items. Think of them as


dynamic shopping lists where you can add, remove, and reorder items.

o Mutable: You can change items, add new ones, or remove existing ones after the
list is created.

o Creating Lists:
 Syntax: my_list = [item1, item2, ...]

o Accessing Elements:

 Indexing: my_list[index] (start from 0, negative index for end).

 Slicing: my_list[start:end] (sub-list).

o Modifying Lists:

 append(): Add an item to the end.

 insert(): Add an item at a specific position.

 remove(): Remove the first occurrence of a value.

 pop(): Remove item at specific index (or last) and return it.

 del keyword: Delete by index or slice.

o Other Useful Methods: sort(), reverse(), count(), index().

 Code Example:

Python

todo_list = ["Buy groceries", "Do laundry", "Call friend"]

print(f"Original list: {todo_list}")

todo_list.append("Walk dog")

print(f"After append: {todo_list}")

todo_list.insert(1, "Pay bills") # Insert at index 1

print(f"After insert: {todo_list}")

# Accessing

print(f"First item: {todo_list[0]}")

print(f"Last item: {todo_list[-1]}")

print(f"Slice (1 to 3): {todo_list[1:4]}")


# Removing

todo_list.remove("Do laundry")

print(f"After remove: {todo_list}")

done_task = todo_list.pop(0) # Pop the first item

print(f"Popped item: '{done_task}', List now: {todo_list}")

todo_list.sort()

print(f"Sorted list: {todo_list}")

 Explanation for Students: Lists are ordered collections, like a checklist. You can change
them by adding, removing, or reordering items. You can access individual items by their
position (index) or grab a portion of the list (slice).

Slide 10: Tuples & Sets: Immutable and Unique Collections

 Title: Tuples & Sets: Special Ways to Store Collections

 Content:

o Tuples:

 Ordered, immutable collections. Once created, you cannot change, add,


or remove items.

 Often used for fixed collections of related data (like coordinates (x, y) or a
record).

 Syntax: my_tuple = (item1, item2) or item1, item2 (packing).

 Tuple packing/unpacking is handy for returning multiple values from


functions.

o Sets:

 Unordered collections of unique elements. Duplicate elements are


automatically removed.
 Useful for checking membership quickly and performing mathematical set
operations (union, intersection, difference).

 Syntax: my_set = {item1, item2} (for non-empty), my_empty_set = set()

 Code Example:

Python

# Tuples

coordinates = (10, 20)

print(f"Coordinates: {coordinates}")

# coordinates[0] = 15 # This would cause an error (immutable)

person_info = ("Alice", 30, "Engineer")

name, age, job = person_info # Tuple unpacking

print(f"Name: {name}, Age: {age}")

# Sets

numbers = [1, 2, 2, 3, 4, 4, 5]

unique_numbers = set(numbers)

print(f"Original list: {numbers}")

print(f"Unique numbers (Set): {unique_numbers}")

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5, 6}

print(f"Union (all unique): {[Link](set2)}")

print(f"Intersection (common): {[Link](set2)}")

 Explanation for Students: Tuples are like lists, but once you create them, you can't
change their contents – they're "fixed." Sets are like unordered bags of items where
every item must be unique, making them great for finding unique things or comparing
collections.

Slide 11: Dictionaries: Key-Value Pairs for Quick Lookups

 Title: Dictionaries: Storing Data in Key-Value Pairs

 Content:

o What are Dictionaries? Unordered collections of items, where each item is a pair
of a key and a value. Think of a real-world dictionary: you look up a word (key) to
find its definition (value).

o Keys must be unique and immutable (like strings, numbers, tuples). Values can be
anything.

o Creating Dictionaries:

 Syntax: my_dict = {"key1": value1, "key2": value2}

o Accessing Values: my_dict[key]

o Modifying Dictionaries:

 Adding/Updating: my_dict[new_key] = new_value

 Removing: del my_dict[key] or my_dict.pop(key)

o Iterating over Dictionaries: Loop through keys, values, or key-value pairs


(.items()).

 Code Example:

Python

student_grades = {"Alice": 95, "Bob": 88, "Charlie": 75}

print(f"Initial grades: {student_grades}")

# Accessing

print(f"Alice's grade: {student_grades['Alice']}")

# Adding/Updating
student_grades["David"] = 92 # Add new student

student_grades["Bob"] = 89 # Update Bob's grade

print(f"Updated grades: {student_grades}")

# Removing

del student_grades["Charlie"]

print(f"After removing Charlie: {student_grades}")

# Iterating

print("\nAll students and grades:")

for name, grade in student_grades.items():

print(f"{name}: {grade}")

 Explanation for Students: Dictionaries are like phone books or address books. Instead of
using numbers (like list indexes), you use unique "keys" (like names) to quickly find their
associated "values" (like phone numbers or grades).

Slide 12: Comprehensions: The Pythonic Shortcut!

 Title: Comprehensions: Building Lists and Dictionaries Fast!

 Content:

o What are Comprehensions? A concise and powerful way to create lists and
dictionaries based on existing iterables (like lists, strings, ranges). They often
replace longer for loops.

o List Comprehensions:

 Syntax: new_list = [expression for item in iterable if condition]

o Dictionary Comprehensions:

 Syntax: new_dict = {key_expression: value_expression for item in iterable


if condition}

 Code Example:
Python

# List Comprehension: Get squares of even numbers from 0 to 9

squares_of_evens = [x**2 for x in range(10) if x % 2 == 0]

print(f"Squares of evens: {squares_of_evens}")

# Dictionary Comprehension: Map words to their lengths

words = ["apple", "banana", "kiwi"]

word_lengths = {word: len(word) for word in words}

print(f"Word lengths: {word_lengths}")

# Filter dictionary based on value

inventory = {"apple": 10, "banana": 2, "milk": 5, "bread": 1}

low_stock_items = {item: qty for item, qty in [Link]() if qty < 3}

print(f"Low stock items: {low_stock_items}")

 Explanation for Students: Comprehensions are a super-efficient "shortcut" in Python.


They let you build new lists or dictionaries in just one line, often by transforming or
filtering items from another list or collection. They're a favorite among experienced
Python developers!

Write a function draw_diamond(size). This function should print a diamond pattern made of
asterisks (*) based on the given size (which represents the widest part of the diamond). Use
nested for loops. The size should ideally be an odd number for a symmetrical diamond.

Create a function create_point(x, y) that takes two numbers x and y and returns them as a tuple
representing a 2D point. Then, outside the function, call it to create a point, and demonstrate
how to unpack the x and y coordinates from the tuple into separate variables for printing.

Define a tuple named student_record that stores a student's (name, age, grade_level). Assign
values to it. Then, print each piece of information individually by accessing it using its index
within the tuple.
Given a list of numbers that contains duplicates (e.g., numbers = [1, 5, 2, 8, 5, 1, 9, 2]), use a set
to efficiently find and print only the unique numbers.

Friend Groups Comparison"

 Description: You have two lists representing people in two different friend groups.
group_a = ["Alice", "Bob", "Charlie", "David"] group_b = ["Charlie", "Eve", "Frank",
"Bob"]

o Convert both lists into sets.

o Find and print the names of people who are in both groups (intersection).

o Find and print the names of people who are in either group (union).

o Find and print the names of people who are in Group A but not in Group B
(difference).

Simple Phone Book"

 Description: Create an empty dictionary called phone_book. Then, add at least three
contact entries, where the key is the name (string) and the value is the phone_number
(string). Demonstrate how to:

o Add a new entry.

o Access a phone number using a name.

o Update an existing phone number.

o Remove an entry.

o Print all names (keys).

o Print all phone numbers (values).

Student Grades Lookup"

 Description: Create a dictionary student_grades where keys are student names (strings)
and values are their scores (integers). Add at least 4-5 student entries.

 Then, write a for loop to iterate through the dictionary and print each student's name
and score in a formatted way.

 Finally, ask the user to enter a student's name, and if that student is in your dictionary,
print their score; otherwise, print a "Student not found" message.
Squared Numbers Dictionary"

 Description: Use a dictionary comprehension to create a dictionary where keys are


numbers from 1 to 5 (inclusive) and values are the square of those numbers.

Filtered Inventory"

 Description: You have an existing dictionary representing an inventory: inventory =


{"apple": 10, "banana": 2, "milk": 5, "bread": 1, "eggs": 12}. Use a dictionary
comprehension to create a new dictionary containing only the items where the quantity
is less than 5 (i.e., low stock items).

Unique Words and Their Lengths"

 Description: Ask the user for a sentence. Convert the sentence to lowercase and remove
any punctuation (like '.', ',', '!', '?'). Then, use a combination of string manipulation, sets,
and dictionary comprehensions to create a dictionary where:

o Keys are the unique words from the sentence.

o Values are the length of each unique word.

Example Output:

Enter a sentence: Python is a great language, isn't it?

# Expected Output (order may vary):

# {'python': 6, 'is': 2, 'a': 1, 'great': 5, 'language': 8, "isn't": 5, 'it': 2}

Student Average Score Calculator"

 Description: Create a program that lets a teacher input student names and multiple
scores for each student.

o Use a while loop to repeatedly ask for a student's name. When the name is
entered, ask for their scores (e.g., "90 85 92" as a single string).

o Store this data in a dictionary where the key is the student's name (string) and
the value is a list of their scores (integers).

o When the teacher types "done" for the name, stop input.
o Then, iterate through your student grades dictionary. For each student, calculate
their average score and print it.

Example Interaction:

Enter student name (or 'done' to finish): Ali

Enter Ali's scores (space-separated): 85 90 78

Enter student name (or 'done' to finish): Sara

Enter Sara's scores (space-separated): 92 95 90 98

Enter student name (or 'done' to finish): done

--- Student Averages ---

Ali: 84.33

Sara: 93.75

Day 5:
Slide 13: Week 2: File Handling, Modules and OOP - File I/O: Reading and Writing Files

 Title: File I/O: Making Your Programs Remember!

 Content:

o File Input/Output (I/O): How your program interacts with files on your computer
(reading data from them, writing data to them).

o Opening Files: open() function.

 Modes: r (read), w (write - overwrites!), a (append - adds to end), x


(create - errors if exists).

o Reading from Files:

 read(): Reads entire file content as a string.


 readline(): Reads one line at a time.

 readlines(): Reads all lines into a list of strings.

o Writing to Files:

 write(): Writes a string to the file.

 writelines(): Writes a list of strings to the file.

o Closing Files: file_object.close() (Important!).

o with open(...) as f:: The best way to handle files! It automatically closes the file
even if errors occur.

 Code Example:

Python

# Writing to a file (overwrites if exists)

with open("my_notes.txt", "w") as file:

[Link]("Today was a great day!\n")

[Link]("I learned about file handling.\n")

print("Content written to my_notes.txt")

# Appending to a file

with open("my_notes.txt", "a") as file:

[Link]("This is an appended line.\n")

print("Content appended to my_notes.txt")

# Reading from a file

print("\nReading file content:")

with open("my_notes.txt", "r") as file:

content = [Link]()

print(content)
 Explanation for Students: File I/O allows your programs to save and load data
permanently, so they "remember" information even after they close. The with open(...)
statement is your best friend here, ensuring files are always closed properly.

Slide 14: Modules & Packages: Building with Reusable Code

 Title: Modules & Packages: Leveraging Code from Others (and Yourself!)

 Content:

o What are Modules? Python files containing functions, classes, and variables.
They help organize your code into separate, reusable units.

o Importing Modules: Bring functions/tools from other files into your current
script.

 Syntax:

Python

import module_name

from module_name import function_name

from module_name import * # Avoid this!

import module_name as alias

o Built-in Modules: Python comes with many powerful modules (math, random,
datetime, os, sys).

o Creating Your Own Modules: Simply save your functions/classes in a .py file, and
you can import them into other scripts!

o Packages: A way to organize related modules into directories.

 Code Example:

Python

import math

import random

from datetime import datetime


# Using math module

radius = 5

area = [Link] * (radius ** 2)

print(f"Area of circle with radius {radius}: {area:.2f}")

# Using random module

dice_roll = [Link](1, 6)

print(f"You rolled a: {dice_roll}")

# Using datetime module

current_time = [Link]()

print(f"Current date and time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")

# Example of a simple custom module (save this in my_utils.py)

# --- my_utils.py ---

# def greet(name):

# return f"Hello, {name} from my_utils!"

# def add(a, b):

# return a + b

# -------------------

# In your main script:

# import my_utils

# print(my_utils.greet("Student"))

# print(my_utils.add(5, 3))
 Explanation for Students: Modules are like toolkits that contain useful code others (or
you!) have written. You import them to use their tools without rewriting everything
yourself. This makes your code cleaner and more powerful!

Section 1: Text File Handling

"Daily Journal"

Description: Write a program that allows the user to append a new journal entry to a file named
[Link]. Each entry should start with the current date and time. If the file doesn't exist, it
should be created.

Concepts Reinforced: Text file writing ('a' mode), open(), with statement, write(), datetime
module ([Link](), .strftime()).

Example [Link] content after a few runs:

2025-07-01 14:30:15 - Had a great day learning Python!

2025-07-01 15:00:20 - Practiced file handling.

Example Interaction:

Enter your journal entry: Today was productive.

Entry added to [Link]!

"File Line Counter"

Description: Write a function count_lines(filepath). This function should take a file path as input,
open the file, count the number of lines it contains, and return that count. Handle the case
where the file might not exist.

Concepts Reinforced: Text file reading ('r' mode), open(), with statement, iterating through file
lines, try-except (for FileNotFoundError).

Example my_story.txt content:

Once upon a time,


in a land far, far away,

there lived a brave programmer.

Example Output:

Python

# Assuming my_story.txt exists with content above

print(f"Lines in my_story.txt: {count_lines('my_story.txt')}")

# Expected Output: Lines in my_story.txt: 3

print(f"Lines in non_existent.txt: {count_lines('non_existent.txt')}")

# Expected Output: Error: File not found. Lines: 0 (or a specific error message you design)

"Word Searcher"

Description: Write a program that asks the user for a filename and a word to search for. It
should read the file line by line and print out any line that contains the search word (case-
insensitive). Also, print the total number of times the word appeared.

Concepts Reinforced: Text file reading, input(), for loop, string methods (.lower(), in), count()
(string method), try-except for file not found.

Example [Link] content:

The only way to do great work is to love what you do.

Python is a powerful language.

Always code as if the guy who ends up maintaining your code will be a violent psychopath.

Example Interaction:

Enter filename: [Link]

Enter word to search: code

Always code as if the guy who ends up maintaining your code will be a violent psychopath.
The word 'code' appeared 2 times.

Section 2: CSV File Handling

"Student Grades CSV Reader"

Description: You are given a CSV file named [Link] with student names and their scores.
Write a program to read this CSV file, calculate the average score for all students, and print it.

Concepts Reinforced: CSV file reading ([Link]), open(), with statement, for loop, type
conversion (int()), list operations (sum(), len()), csv module.

Example [Link] content:

Code snippet

Name,Score

Alice,90

Bob,85

Charlie,92

David,78

Example Output:

Average score: 86.25

"Product Inventory CSV Creator"

Description: Write a program that allows a user to input product name and quantity repeatedly.
After they are done (e.g., by typing 'done' for the name), save all the entered product data into
a new CSV file named [Link]. The first line of the CSV should be headers: "Product
Name", "Quantity".

Concepts Reinforced: CSV file writing ([Link], 'w' mode), open(), with statement, while loop,
input(), lists, csv module.

Example [Link] content after interaction:

Code snippet
Product Name,Quantity

Apples,50

Milk,10

Bread,5

Example Interaction:

Enter product name (or 'done' to finish): Apples

Enter quantity: 50

Enter product name (or 'done' to finish): Milk

Enter quantity: 10

Enter product name (or 'done' to finish): done

Inventory saved to [Link]!

Section 3: Modules (General Use)

"Random Password Generator"

Description: Write a function generate_password(length). This function should generate a


random password of a specified length using a mix of uppercase letters, lowercase letters, digits,
and special characters.

Concepts Reinforced: Functions (def, parameters, return), random module ([Link](),


[Link](), [Link]()), string module (string.ascii_letters, [Link],
[Link]), for loop (or list comprehension), string concatenation.

Example Output:

Python

print(generate_password(10)) # Expected: A random 10-character password like "sP9!x$F2a@"

print(generate_password(12)) # Expected: Another random 12-character password

"Area of a Circle Calculator"


Description: Ask the user for the radius of a circle. Use the math module to calculate and print
the circle's area (A=

pir

) and circumference (C=2

pir). Format the output to two decimal places.

Concepts Reinforced: input(), type conversion (float()), math module ([Link], [Link]() or
**), print() formatting (.2f).

Example Output:

Enter the radius of the circle: 5

Area: 78.54

Circumference: 31.42

Section 4: Combined Challenges

"Expense Tracker" (Text File + Functions + Datetime)

Description: Create a simple expense tracker.

Function 1: add_expense(filename, amount, description): Appends a new expense to a file (e.g.,


[Link]). Each entry should include the current date/time, amount, and description.

Function 2: view_expenses(filename): Reads and prints all expenses from the file.

Function 3: get_total_expenses(filename): Reads the file, sums up all expense amounts, and
returns the total.

Use a main while loop to present a menu to the user (Add, View, Total, Exit).

Concepts Reinforced: Functions, while loop, input(), file handling (read/write/append), datetime
module, string splitting/parsing, type conversion, error handling (e.g., for non-numeric
amounts).

Example [Link] entry:

2025-07-01 16:05:30,50.00,Groceries
2025-07-01 16:10:15,15.50,Coffee

Example Interaction:

Expense Tracker Menu:

1. Add Expense

2. View Expenses

3. Get Total Expenses

4. Exit

Enter your choice: 1

Enter amount: 50.00

Enter description: Groceries

Expense added!

Enter your choice: 3

Total expenses: $65.50

"Student Data Analyzer" (CSV + Dictionaries + Functions)

Description: Read student data from a CSV file (like student_data.csv) which contains "Name",
"Age", and "Grade".

Function 1: load_student_data(filepath): Reads the CSV and returns a list of dictionaries, where
each dictionary represents a student.

Function 2: get_average_age(student_list): Takes the list of student dictionaries and calculates


the average age.

Function 3: get_students_by_grade(student_list, grade_filter): Takes the list of student


dictionaries and a grade level, returning a list of names of students in that grade.

Demonstrate using these functions after loading the data.

Concepts Reinforced: CSV reading ([Link] is ideal here, or [Link] followed by


manual dictionary creation), lists of dictionaries, functions, loops, type conversion, conditional
logic, dictionary access.
Example student_data.csv:

Code snippet

Name,Age,Grade

Alice,16,10

Bob,15,9

Charlie,16,10

David,17,11

Example Output:

Python

# Assuming student_data.csv exists with content above

students = load_student_data("student_data.csv")

print(f"Average age: {get_average_age(students):.1f}")

# Expected: Average age: 16.0

grade_10_students = get_students_by_grade(students, 10)

print(f"Students in Grade 10: {grade_10_students}")

# Expected: Students in Grade 10: ['Alice', 'Charlie']

Day 6:
Slide 15: Week 2: Object-Oriented Programming (OOP) - Part 1 (Classes & Objects)

 Title: OOP Part 1: Classes & Objects - Building Blueprints for Your Code

 Content:

o What is OOP? Object-Oriented Programming is a way to structure your code by


modeling real-world things as "objects."
 Objects: Individual instances of a "thing" (like a specific car: "my red
Toyota").

 Classes: Blueprints or templates for creating objects (like the design plans
for any car).

o Encapsulation: Bundling data (attributes) and the methods (functions) that


operate on that data into a single unit (the object). It hides internal details.

o Attributes: Data or characteristics associated with an object (e.g., a car's color,


speed).

o Methods: Functions that belong to an object and describe its actions (e.g., a car's
start() or drive() method).

o __init__ Method (Constructor): A special method that runs automatically when


you create a new object. It's used to set up the object's initial attributes.

o self Keyword: Refers to the instance of the object itself. It's the first parameter in
all instance methods.

 Code Example:

Python

class Car:

# The constructor method

def __init__(self, make, model, year):

[Link] = make # Instance attribute

[Link] = model # Instance attribute

[Link] = year # Instance attribute

self.is_started = False # Default state attribute

# Method to start the car

def start(self):

if not self.is_started:

self.is_started = True
print(f"The {[Link]} {[Link]} {[Link]} is now started.")

else:

print("The car is already running.")

# Method to stop the car

def stop(self):

if self.is_started:

self.is_started = False

print(f"The {[Link]} {[Link]} is now stopped.")

else:

print("The car is already off.")

# Creating objects (instances of the Car class)

my_car = Car("Toyota", "Camry", 2020)

friends_car = Car("Honda", "Civic", 2023)

# Accessing attributes and calling methods

print(f"My car is a {my_car.make} {my_car.model}.")

my_car.start()

friends_car.start()

my_car.stop()

my_car.stop() # Demonstrates already off

 Explanation for Students: OOP helps us design programs like we design real-world
things. A "class" is like a blueprint for an object, describing its characteristics (attributes)
and what it can do (methods). When you create an "object," you're making a specific
instance from that blueprint.
"Book Class"

 Description:

o Define a class named Book.

o The __init__ method should accept title, author, and isbn as arguments and
assign them as instance attributes.

o Add a method display_info() that prints the book's title, author, and ISBN in a
user-friendly format.

o Outside the class, create at least two Book objects with different details.

o Call the display_info() method for each of your book objects.

 Concepts Reinforced: Class definition, __init__ method, instance attributes, instance


methods, creating objects, calling methods.

 Example Usage:

Python

# Define the Book class above

book1 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", "978-0345391803")

book2 = Book("Pride and Prejudice", "Jane Austen", "978-0141439518")

book1.display_info()

# Expected Output:

# Title: The Hitchhiker's Guide to the Galaxy

# Author: Douglas Adams

# ISBN: 978-0345391803
book2.display_info()

# Expected Output:

# Title: Pride and Prejudice

# Author: Jane Austen

# ISBN: 978-0141439518

"Rectangle Class"

 Description:

o Define a class named Rectangle.

o The __init__ method should take width and height as arguments and assign
them as instance attributes.

o Add a method calculate_area() that returns the area of the rectangle.

o Add a method calculate_perimeter() that returns the perimeter of the rectangle.

o Add a method is_square() that returns True if the rectangle is a square (width
equals height), False otherwise.

o Create a Rectangle object and a Square (another Rectangle object with equal
sides).

o Print their areas, perimeters, and whether they are squares.

 Concepts Reinforced: Class definition, __init__ method, instance attributes, instance


methods, self keyword, arithmetic calculations, conditional logic (if/else).

Basic Bank Account Class"

 Description:

o Define a class named BankAccount.

o The __init__ method should accept account_number, account_holder_name,


and an initial balance (default to 0 if not provided). Assign these as instance
attributes.
o Add a method deposit(amount): Adds the amount to the balance. Print a success
message and the new balance. Handle cases where the deposit amount is not
positive.

o Add a method withdraw(amount): Subtracts the amount from the balance. Print
a success message and the new balance. Handle cases where the withdrawal
amount is not positive or if there are insufficient funds.

o Add a method get_balance(): Returns the current balance.

o Create a BankAccount object. Perform a deposit, a successful withdrawal, and an


unsuccessful withdrawal. Print the balance after each operation.

 Concepts Reinforced: Class definition, __init__ method (with default parameters),


instance attributes, instance methods, self keyword, arithmetic operations, conditional
logic (if/else), state management within an object.

Day 7:
Slide 16: OOP Part 2: Inheritance & Polymorphism - Building on Existing Blueprints

 Title: OOP Part 2: Inheritance & Polymorphism - Building Smarter, Not Harder

 Content:

o Inheritance: Allows a new class (child/subclass) to take on the attributes and


methods of an existing class (parent/superclass). This promotes code reuse and
creates a "is-a" relationship (e.g., a Dog is a Animal).

 super() function: Used in a child class to call methods or access attributes


from its parent class.

 Method Overriding: A subclass can provide its own implementation for a


method that is already defined in its superclass.

o Polymorphism: The ability of different objects (from different classes) to respond


to the same method call in their own specific way. (e.g., make_sound() can be
different for Dog, Cat, Bird).

o Class Variables vs. Instance Variables:

 Instance Variables: Unique to each object (e.g., my_car.color).


 Class Variables: Shared by all objects of that class (e.g., Car.num_wheels).

 Code Example:

Python

class Shape: # Parent class

def __init__(self, color):

[Link] = color

def describe(self):

print(f"This is a {[Link]} shape.")

def area(self): # Placeholder method for area calculation

raise NotImplementedError("Subclasses must implement 'area' method.")

class Circle(Shape): # Child class inheriting from Shape

def __init__(self, color, radius):

super().__init__(color) # Call parent's constructor

[Link] = radius

def area(self): # Overriding the area method

return [Link] * ([Link] ** 2)

def describe(self): # Overriding to add more detail

print(f"This is a {[Link]} circle with radius {[Link]}.")

class Rectangle(Shape): # Another child class

def __init__(self, color, width, height):


super().__init__(color)

[Link] = width

[Link] = height

def area(self): # Overriding the area method

return [Link] * [Link]

# Need to import math for pi

import math

# Demonstrating Polymorphism

my_circle = Circle("blue", 7)

my_rectangle = Rectangle("red", 10, 5)

shapes = [my_circle, my_rectangle]

for shape in shapes:

[Link]() # Calls specific describe method for each shape

print(f"Area: {[Link]():.2f}\n") # Calls specific area method

 Explanation for Students: Inheritance lets you create new "child" classes that
automatically get features from a "parent" class, saving you time. Polymorphism means
different objects can perform the same action in their own unique way, making your
code flexible and powerful.

In the above example, we have created a superclass: Polygon and two subclasses: Square and
Circle. Notice the use of the render() method.

The main purpose of the render() method is to render the shape. However, the process of
rendering a square is different from the process of rendering a circle.
Hence, the render() method behaves differently in different classes. Or, we can say render() is
polymorphic.

Basic Inheritance & Method Overriding

1. "Animal Sounds"

o Description:

 Define a base class named Animal.

 Its __init__ method should take a name and set it as an instance


attribute.

 It should have a method make_sound() that prints a generic


animal sound, e.g., "The animal makes a sound."

 Define a subclass named Dog that inherits from Animal.

 Its __init__ method should take name and breed. It should call the
Animal's __init__ using super().

 It should override the make_sound() method to print "[Dog's


Name] barks loudly!".

 Define another subclass named Cat that inherits from Animal.

 Its __init__ method should take name and color. It should call the
Animal's __init__ using super().

 It should override the make_sound() method to print "[Cat's


Name] meows softly.".

 Create one Animal object, one Dog object, and one Cat object. Call
make_sound() for each.

o Concepts Reinforced: Inheritance (class Child(Parent)), super().__init__(),


Method Overriding, Creating instances of parent and child classes.

o Example Usage:

Python

# Define Animal, Dog, Cat classes above


generic_animal = Animal("Leo")

my_dog = Dog("Buddy", "Golden Retriever")

my_cat = Cat("Whiskers", "Tabby")

generic_animal.make_sound()

# Expected Output: The animal makes a sound.

my_dog.make_sound()

# Expected Output: Buddy barks loudly!

my_cat.make_sound()

# Expected Output: Whiskers meows softly.

Polymorphism in Action

1. "Geometric Shapes Area Calculator"

o Description:

 Define a base class named Shape.

 Its __init__ method should take a color.

 It should have a placeholder method calculate_area() that simply


returns 0 (or raises NotImplementedError for more advanced
students).

 It should have a describe() method that prints f"This is a


{[Link]} shape."

 Define a subclass named Circle that inherits from Shape.

 Its __init__ method should take color and radius. Call


super().__init__().

 It must override calculate_area() to return the area of a circle


(pir2). (You'll need to import math).
 It must override describe() to print more specific information, e.g.,
f"This is a {[Link]} circle with radius {[Link]}."

 Define a subclass named Rectangle that inherits from Shape.

 Its __init__ method should take color, width, and height. Call
super().__init__().

 It must override calculate_area() to return the area of a rectangle.

 It must override describe() to print more specific information, e.g.,


f"This is a {[Link]} rectangle of width {[Link]} and height
{[Link]}."

 Create a list containing at least one Circle object and one Rectangle
object.

 Use a for loop to iterate through this list. For each shape in the list, call its
describe() method and print its calculate_area(). Observe how the same
method calls yield different results based on the object's type
(polymorphism).

o Concepts Reinforced: Inheritance, Method Overriding, Polymorphism (different


objects responding to the same method call uniquely), import math, using a list
to demonstrate polymorphism.

Practical Inheritance Hierarchy

1. "Employee Management System (Simplified)"

o Description:

 Define a base class Employee.


 __init__ takes name and employee_id.

 display_info() prints general employee details.

 calculate_yearly_salary() returns a base salary (e.g., 50000).

 Define a subclass Manager inheriting from Employee.

 __init__ takes name, employee_id, and department. Call


super().__init__().

 Override display_info() to include the department.

 Override calculate_yearly_salary() to add a bonus (e.g., base


salary + 10000).

 Define a subclass Developer inheriting from Employee.

 __init__ takes name, employee_id, and programming_language.


Call super().__init__().

 Override display_info() to include the programming language.

 Override calculate_yearly_salary() to add a smaller bonus (e.g.,


base salary + 5000).

 Create instances of Employee, Manager, and Developer.

 Call display_info() and calculate_yearly_salary() for each instance.

 Create a list of these diverse employee objects and use a loop to display
all their info and salaries, showcasing polymorphism.

o Concepts Reinforced: Inheritance, super(), Method Overriding, Polymorphism in


a business context, instance attributes specific to subclasses.

Class Variables vs. Instance Variables: Who Owns the Data?

In Python, when you define attributes within a class, you need to understand whether that
attribute belongs to each individual object (instance) or to the class itself. This distinction is
critical for managing data effectively.

1. Instance Variables
 Definition: These are variables whose values are unique to each instance (object) of a
class. Every object gets its own copy of these variables.

 Creation: They are typically defined inside the __init__ method using the self keyword
(e.g., self.attribute_name = value).

 Ownership: Owned by individual objects.

 Access: Accessed via an object instance (e.g., my_object.attribute_name).

2. Class Variables

 Definition: These are variables whose values are shared among all instances (objects) of
a class. There is only one copy of a class variable, no matter how many objects you
create.

 Creation: They are defined directly inside the class body, but outside of any method.

 Ownership: Owned by the class itself.

 Access: Can be accessed either via the class name (e.g., ClassName.attribute_name) or
via an object instance (e.g., my_object.attribute_name), though accessing via the class
name is preferred for clarity when reading.

Key Differences:

Feature Instance Variables Class Variables

Ownership Each object has its own copy. Shared by all objects of the class.

Inside methods (usually __init__) using


Declaration Directly inside the class body.
self..

Value Can be different for each object. Same for all objects (unless changed).

Only one memory location for the


Memory Each object allocates space for them.
class.
Day 8:
Slide 17: Introduction to Pygame: Your First Game Window!

 Title: Pygame Basics: Bringing Your Programs to Life Visually!

 Content:

o What is Pygame? A popular Python library specifically designed for making 2D


games and interactive multimedia applications. It handles graphics, sound, and
user input easily.

o Installation: You install Pygame using Python's package installer: pip install
pygame

o Basic Pygame Structure:

1. Import: import pygame

2. Initialize: [Link]() (starts Pygame modules)

3. Create Display: Set up the game window size.

4. Game Loop: The heart of every game! It constantly:

 Checks for user input (events).

 Updates game logic (movement, scores).

 Draws everything on the screen.

5. Update Display: Shows the newly drawn frame.

6. Control Frame Rate: Ensures the game runs smoothly.

 Code Example:

Python

import pygame

# 1. Initialize Pygame

[Link]()

# 2. Set up the display (window)


screen_width = 800

screen_height = 600

screen = [Link].set_mode((screen_width, screen_height))

[Link].set_caption("My First Pygame Window")

# Define colors (RGB values)

BLUE = (0, 0, 255)

WHITE = (255, 255, 255)

# Game loop flag

running = True

# Create a clock object to control frame rate

clock = [Link]()

# 3. Game Loop

while running:

for event in [Link](): # Check for events (like closing window)

if [Link] == [Link]:

running = False # Stop the loop if user clicks close button

# 4. Drawing

[Link](WHITE) # Fill background with white

[Link](screen, BLUE, (50, 50, 100, 75)) # Draw a blue rectangle

# 5. Update the display


[Link]()

# 6. Control frame rate

[Link](60) # Limit to 60 frames per second

# Quit Pygame

[Link]()

print("Pygame window closed.")

 Explanation for Students: Pygame is your gateway to making visual programs! It helps
you create a window, draw shapes, and respond to things like mouse clicks and key
presses. The "game loop" is like the engine of your game, constantly running to keep
everything updated.

Slide 18: Pygame: Drawing Shapes and Simple Interaction

 Title: Pygame: Drawing Graphics & Responding to Input!

 Content:

o Drawing Primitives: Pygame has functions to draw basic shapes like rectangles,
circles, lines, and polygons.

 Syntax: [Link](surface, color, rect_tuple, width)

 Syntax: [Link](surface, color, center_tuple, radius, width)

o Colors: Defined as a tuple of Red, Green, Blue (RGB) values, each from 0 to 255.

o Simple Interaction (Event Handling): The [Link]() list contains all user
actions. You check [Link] to see what happened.

 [Link]: User clicked the close button.

 [Link]: A key on the keyboard was pressed. You can check


[Link] to see which key.

 Code Example:

Python
import pygame

[Link]()

screen_width = 600

screen_height = 400

screen = [Link].set_mode((screen_width, screen_height))

[Link].set_caption("Moving Square")

# Colors

RED = (255, 0, 0)

BLACK = (0, 0, 0)

# Square properties

square_x = 250

square_y = 150

square_size = 50

square_speed = 5

running = True

clock = [Link]()

while running:

for event in [Link]():

if [Link] == [Link]:

running = False

elif [Link] == [Link]:


if [Link] == pygame.K_LEFT:

square_x -= square_speed

elif [Link] == pygame.K_RIGHT:

square_x += square_speed

elif [Link] == pygame.K_UP:

square_y -= square_speed

elif [Link] == pygame.K_DOWN:

square_y += square_speed

# Keep square on screen

square_x = max(0, min(square_x, screen_width - square_size))

square_y = max(0, min(square_y, screen_height - square_size))

[Link](BLACK) # Clear screen each frame

[Link](screen, RED, (square_x, square_y, square_size, square_size))

[Link]()

[Link](60)

[Link]()

 Explanation for Students: We can draw various shapes using [Link] functions,
specifying their color (using RGB values) and position. Importantly, Pygame lets your
program listen for user actions like pressing keys, allowing you to create interactive
experiences like moving objects on the screen!

Slide 19: Introduction to NumPy: Powering Numerical Computing

 Title: NumPy: The Powerhouse for Numbers!

 Content:
o What is NumPy? A fundamental Python library for high-performance numerical
computing. It's the backbone for data science, machine learning, and scientific
computing.

o Why NumPy Arrays (ndarray)?

 Speed & Memory: Much faster and more memory-efficient than standard
Python lists for large numerical operations.

 N-dimensional: Can handle not just lists, but tables (2D), cubes (3D), and
higher dimensions.

 Homogeneous: All elements in a NumPy array must be of the same data


type.

o Creating Arrays:

 From Python lists: [Link]([1, 2, 3])

 Special arrays: [Link](), [Link](), [Link](), [Link]()

o Basic Array Attributes:

 [Link]: Dimensions of the array (e.g., (3,) for 1D, (2, 3) for 2D).

 [Link]: Number of dimensions.

 [Link]: Total number of elements.

 Code Example:

Python

import numpy as np # Convention to import numpy as np

# Creating arrays

my_list = [1, 2, 3, 4, 5]

my_array = [Link](my_list)

print(f"Array from list: {my_array}")

# Create an array of zeros (2 rows, 3 columns)

zeros_array = [Link]((2, 3))


print(f"\nZeros array (2x3):\n{zeros_array}")

# Create an array with a range of numbers

range_array = [Link](10, 20, 2) # Start, Stop (exclusive), Step

print(f"\nRange array: {range_array}")

# Array attributes

print(f"\nShape of zeros_array: {zeros_array.shape}")

print(f"Dimensions of zeros_array: {zeros_array.ndim}")

print(f"Size of zeros_array: {zeros_array.size}")

# Example of homogeneous data type

mixed_list = [1, 2.5, "hello"]

mixed_array = [Link](mixed_list) # NumPy will try to find a common type (e.g., string)

print(f"\nMixed array (converted to string type): {mixed_array}, dtype: {mixed_array.dtype}")

 Explanation for Students: NumPy is a crucial library for working with large amounts of
numbers quickly. It uses special "arrays" that are super-efficient compared to normal
Python lists, especially when you're doing math with many numbers, which is essential
for things like AI and data analysis.

Slide 20: NumPy: Indexing, Slicing & Operations

 Title: NumPy: Manipulating & Calculating with Arrays

 Content:

o Array Indexing & Slicing: Similar to lists, but extends to multiple dimensions for
2D (tables) or 3D (cubes) arrays.

 my_array[row_index, col_index] for 2D.

 my_array[start_row:end_row, start_col:end_col] for 2D slices.


o Basic Array Operations: NumPy allows "element-wise" operations, meaning
operations apply to each element of the array, very efficiently.

 +, -, *, / (perform operation on each corresponding element).

 Mathematical functions (e.g., [Link](), [Link](), [Link]()).

o Reshaping Arrays: Changing the dimensions of an array without changing its


data.

 [Link](new_shape_tuple)

 Code Example:

Python

import numpy as np

# Create a 2D array (matrix)

matrix = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(f"Original Matrix:\n{matrix}")

# Indexing

print(f"\nElement at (0, 0): {matrix[0, 0]}") # First row, first column

print(f"Element at (1, 2): {matrix[1, 2]}") # Second row, third column (value 6)

# Slicing

print(f"\nFirst row: {matrix[0, :]}") # All columns in first row

print(f"Second column: {matrix[:, 1]}") # All rows in second column

print(f"Sub-matrix (top-left 2x2):\n{matrix[0:2, 0:2]}")

# Element-wise operations

scaled_matrix = matrix * 10

print(f"\nMatrix multiplied by 10:\n{scaled_matrix}")


# Aggregate operations

daily_temps = [Link]([25, 27, 26, 28, 29, 24, 30])

print(f"\nDaily temperatures: {daily_temps}")

print(f"Average temp: {[Link](daily_temps):.2f}°C")

print(f"Max temp: {[Link](daily_temps)}°C")

print(f"Min temp: {[Link](daily_temps)}°C")

 Explanation for Students: You can access parts of NumPy arrays using indexing and
slicing, just like lists, but you can also do it for multiple dimensions (rows and columns!).
The coolest part is how you can perform calculations on entire arrays at once, making
complex math incredibly simple and fast.

Section 1: NumPy Arrays for Visual Data (Pygame Grids)

1. "Colorful Clickable Grid"

o Description:

 Create a Pygame window.

 Represent a grid of colored cells using a 2D NumPy array (e.g., (rows, cols,
3) for RGB colors, or (rows, cols) for color indices).

 Draw this grid on the Pygame screen.

 When the user clicks on a cell, change its color in the NumPy array, and
then redraw the grid to show the change.

o Concepts Reinforced: Pygame basics (window, loop, drawing [Link]),


NumPy 2D arrays, array indexing for modification, [Link].get_pos(),
converting mouse coordinates to grid indices.
o Hints:

 Define CELL_SIZE (e.g., 20 pixels).

 Calculate num_rows = screen_height // CELL_SIZE and num_cols =


screen_width // CELL_SIZE.

 Initialize your NumPy array with a default color (e.g.,


[Link]((num_rows, num_cols, 3), dtype=np.uint8) for black).

 Inside the game loop, when [Link] ==


[Link], get mouse_x, mouse_y = [Link].

 Convert these to grid_row = mouse_y // CELL_SIZE and grid_col =


mouse_x // CELL_SIZE.

 Update color_grid[grid_row, grid_col] to a new RGB tuple (e.g., (255, 0, 0)


for red).

 Loop through color_grid using nested for loops (or more efficiently using
NumPy slicing if comfortable) to draw each [Link].

o Example Output: A window with a grid. Clicking a square changes its color.

Section 2: NumPy for Game Object State & Movement

1. "Bouncing Circle with NumPy Physics"

o Description:

 Create a Pygame window.

 Represent a single circle's position as a 1D NumPy array (e.g., [Link]([x,


y])).

 Represent its velocity as another 1D NumPy array (e.g., [Link]([vx, vy])).

 In the game loop, update the circle's position by adding its velocity.

 Implement basic bouncing: if the circle hits the screen edges, reverse the
corresponding velocity component.

 Draw the circle at its updated position.

o Concepts Reinforced: Pygame basics (drawing circles), NumPy 1D arrays for


vectors, element-wise array addition, conditional logic for boundary checks,
updating values in a NumPy array.
o Hints:

 Initialize position = [Link]([screen_width / 2, screen_height / 2],


dtype=float).

 Initialize velocity = [Link]([3, 2], dtype=float).

 Update: position += velocity.

 For bouncing: if position[0] - radius < 0 or position[0] + radius >


screen_width: velocity[0] *= -1. Do similar for y coordinate.

 Use int(position[0]), int(position[1]) when drawing, as Pygame expects


integer coordinates.

o Example Output: A circle bouncing off the edges of the Pygame window.

Section 3: Combined Challenges (More Advanced)

1. "Starfield Simulator"

o Description:

 Create a Pygame window.

 Represent many "stars" (small points or circles) using a 2D NumPy array.


Each row in the array should store the [x, y, z] coordinates of a star, where
z can represent its "depth" or speed.

 In the game loop, update each star's x and y position based on its z
coordinate (e.g., make stars with smaller z (further away) move slower,
and stars with larger z (closer) move faster).

 Make stars "wrap around" the screen when they go off-screen.

 Draw each star as a small circle or point. You can optionally make their
color or size depend on their z value.

o Concepts Reinforced: Pygame drawing, NumPy 2D arrays, efficient array


operations (broadcasting or vectorization for updates), modular arithmetic (%)
for wrapping coordinates, managing multiple objects.

o Hints:

 Initialize stars = [Link](NUM_STARS, 3) *


[Link]([screen_width, screen_height, MAX_Z_VALUE]). NUM_STARS
could be 100-500.
 To update x and y based on z: stars[:, 0] += stars[:, 2] * SPEED_FACTOR
and stars[:, 1] += stars[:, 2] * SPEED_FACTOR.

 For wrapping: stars[:, 0] %= screen_width and stars[:, 1] %=


screen_height.

 When drawing, [Link](screen, color, (int(x), int(y)), size). size


could be int(stars[i, 2] / SOME_FACTOR).

o Example Output: A classic starfield effect, with stars moving and looping.

2. "Simple Bar Chart Visualizer"

o Description:

 Create a Pygame window.

 Generate a 1D NumPy array of random integer "data points" (e.g., 5-10


values between 10 and 200).

 Draw these data points as a simple bar chart on the Pygame screen. Each
value in the NumPy array corresponds to the height of a bar.

 Add labels for the axes or values on top of the bars (requires
[Link]).

o Concepts Reinforced: Pygame drawing ([Link], [Link]), NumPy


1D arrays ([Link]), for loop (to draw bars), basic scaling and
positioning logic.

o Hints:

 Define BAR_WIDTH.

 The x position of each bar will be index * BAR_WIDTH.

 The y position will be screen_height - bar_height (because Pygame's y-


axis increases downwards).

 Use [Link]() and [Link]() to create text surfaces for


labels.

o Example Output: A Pygame window displaying a simple bar chart based on


random NumPy data.

Reverse & Reshape"


Description: Given a 1D array data = [Link](1, 10):

Reverse the order of elements in data and print the reversed array.

Reshape the original data array into a 3x3 2D array and print it.

Concepts Reinforced: Slicing for reversal ([::-1]), reshape().

Example Output:

Original data: [1 2 3 4 5 6 7 8 9]

Reversed data: [9 8 7 6 5 4 3 2 1]

Reshaped 3x3:

[[1 2 3]

[4 5 6]

[7 8 9]]

"Element-wise Operations"

 Description: Given two arrays arr1 = [Link]([1, 2, 3]) and arr2 = [Link]([4, 5, 6]):

o Perform element-wise addition, subtraction, multiplication, and division of arr1


by arr2. Print each result.

o Calculate arr1 raised to the power of 3 (element-wise).

 Concepts Reinforced: Element-wise arithmetic operators (+, -, *, /, **).

 Example Output:

 Addition: [5 7 9]

 Subtraction: [-3 -3 -3]

 Multiplication: [ 4 10 18]

 Division: [0.25 0.4 0.5 ]

Power of 3: [ 1 8 27]

Common questions

Powered by AI

The document uses NumPy to manage game object states and facilitate efficient calculations, such as representing positions and velocities with 1D arrays or managing multiple object positions with 2D arrays. Benefits include high performance due to memory-efficient operations and ease of performing vectorized calculations. For example, in a starfield simulator, NumPy supports rapid updates of an array representing star positions, making it ideal for simulating movement and tracking object states across frames .

The document suggests storing student scores using data structures such as a list of lists or a list of dictionaries. Key concepts involved include functions for calculating the average and highest scores, employing a while loop for data entry, type conversion with int(), using lists for data storage, and using for loops for calculation within functions. Arithmetic operations like len() and max() are also crucial for producing the required summaries .

The document recommends validating user inputs to ensure they are positive for deposits and that there are sufficient funds for withdrawals. This is crucial to maintain the system’s integrity and prevent errors such as attempting to withdraw more funds than are available, thereby preventing overdraft issues. Using input validation helps ensure that the banking system functions correctly and securely without processing invalid transactions .

The document outlines creating a random password generator using the random module and string module. It recommends defining a function generate_password(length) using random.choice() or random.sample() to select characters from a mix of uppercase, lowercase letters, digits, and special characters. The approach emphasizes understanding of functions with parameters and return values, usage of string module for character selection, and leveraging list comprehensions and string concatenation .

The document describes using Pygame for graphics and user interaction, where a main loop handles events like keyboard inputs or window closing actions, processed using pygame.event.get(). For example, KEYDOWN events modify game object states like position in response to arrow keys, while pygame.QUIT terminates the program. Event handling is significant as it allows dynamic interaction within games, creating responsive experiences by adapting the game state according to user actions .

For string manipulation, the document outlines accessing and modifying strings using indexing, slicing, and various string methods. Key methods include len() for string length, case modification methods like lower(), upper(), and capitalize(), and common operations such as strip() for whitespace removal, find()/index() for substring location, replace() for substitutions, split()/join() for word operations, providing a comprehensive toolbox for textual data processing .

The 'Student Data Analyzer' uses csv.DictReader to read CSV files and convert rows into dictionaries, where each dictionary represents a student's data. Functions like load_student_data() load the data, while get_average_age() calculates the average age, and get_students_by_grade() filters students by grade. This approach allows easy access to student attributes by keys, simplifies filtering and aggregation operations through dictionary operations, and encapsulates functionality within specific utilities for enhanced clarity and reusability .

In the 'Expense Tracker' system, functions are used to encapsulate key operations such as adding expenses, viewing expenses, and calculating total expenses. The add_expense function appends a new transaction to a file, including details like date/time, amount, and description. The view_expenses function reads from the file and displays all entries, while get_total_expenses calculates the sum of recorded expenses. These functions reinforce modular programming by isolating tasks into separate units, improving code readability and maintainability .

The document uses OOP concepts by defining a 'Car' class with attributes such as make, model, and year, initialized via the __init__ constructor. Methods like start() and stop() within this class control the car's state. This encapsulates the data and methods related to a car within an object, allowing multiple instances with distinct states. Such organization results in more structured and maintainable code, enhancing simulation realism by reflecting real-world properties of cars .

The process involves opening a CSV file named grades.csv using the csv.reader in a with statement to ensure proper file handling. The program reads student names and scores, converting the list of scores into integers for calculation purposes. List operations like sum() and len() are used to compute the average score efficiently. This reinforces the understanding of the CSV module, type conversion and basic list operations .

You might also like