Lesson Notes By Weeks and Term v5 - Grade 12

Programming for problem solving and projects – Week 8 focus

Download the Lessonotes Mobile South Africa app for faster lesson access on Android and iPhone.

Subject: Information Technology

Class: Grade 12

Term: 1st Term

Week: 8

Theme: General lesson support

Lesson Video

This page supports the lesson note with a companion video and a short classroom-ready summary.

For class groups and homework, share this lesson page so learners also get the summary, objectives, and full lesson context.

Performance objectives

Lesson summary

This week, we're diving deeper into programming for problem-solving, specifically focusing on practical project development. Programming isn't just about writing lines of code; it's about using logic and creativity to solve real-world problems. In South Africa, we face unique challenges, from managing resources like water and electricity to improving access to education and healthcare. By mastering programming skills, you'll be equipped to develop innovative solutions to these problems and contribute to a more sustainable and equitable future.

Lesson notes

2.1 Data Structures: Arrays, Lists, and Dictionaries Data structures are fundamental to organizing and managing data efficiently within a program. We'll revisit these in the context of problem-solving.

Arrays (or Lists): Ordered collections of elements, typically of the same data type. Think of an array as a set of numbered containers, each holding a single value. In Python, lists are dynamically sized, meaning you don't need to specify the size upfront.

Example:* Storing a list of student names in a class. ```python student_names = ["Thando", "Aisha", "Sipho", "Zanele"] print(student_names[0]) # Output: Thando (accessing the first element) ``` Why use a list? Because we need to keep track of multiple student names in a specific order. How is it done? By assigning the names to the list student_names.

Dictionaries: Collections of key-value pairs.

Think of a real-world dictionary: you look up a word (the key) to find its definition (the value). Dictionaries provide fast lookups by key.

Example:* Storing student IDs and their corresponding grades. ```python student_grades = { "STD001": 85, "STD002": 92, "STD003": 78 } print(student_grades["STD002"]) # Output: 92 (accessing the grade for STD002) ``` Why use a dictionary? Because we need to quickly find a student's grade based on their ID. How is it done? By assigning keys that relate to student ID's to values that represent the grade for that student. 2.2 Modular Programming: Functions/Procedures Modular programming involves breaking down a complex problem into smaller, self-contained modules (functions or procedures). This makes code easier to read, understand, test, and maintain. Functions promote code reuse, reducing redundancy.

Example:* Calculating the average of a list of numbers. ```python def calculate_average(numbers): """Calculates the average of a list of numbers.

Args: numbers: A list of numbers.

Returns: The average of the numbers. """ if not numbers: # Check if the list is empty return 0 # Avoid division by zero total = sum(numbers) average = total / len(numbers) return average grades = [75, 80, 90, 85, 95] average_grade = calculate_average(grades) print(f"The average grade is: {average_grade}") ``` Why use a function? Because we might need to calculate the average in multiple places in our program. How? By writing a function to perform the calculation and then call it as needed. This example implements a function that will calculate an average only if there are elements in the list; otherwise, to avoid division by zero, the function returns zero. The docstring in triple quotes is crucial for documentation. 2.3 Error Handling: Try-Except Blocks Error handling is crucial for creating robust programs that can gracefully handle unexpected situations. The `try-except` block allows you to anticipate potential errors and provide alternative code to execute if an error occurs.

Example:* Handling a `ValueError` when converting user input to an integer. ```python try: age = int(input("Enter your age: ")) if age max_num: max_num = num return max_num Example usage: numbers = [10, 5, 20, 15] max_number = find_max(numbers) print(f"The maximum number is: {max_number}") # Output: The maximum number is: 20 ```

Commentary: This function first checks if the input list is empty. If it is, it returns `None`. Otherwise, it initializes `max_num` to the first element of the list and then iterates through the rest of the list, updating `max_num` whenever it finds a larger number. The docstring clearly describes the function's purpose, arguments, and return value.

Question 2: Create a program that asks the user to enter a series of numbers (separated by spaces) and then calculates and prints the average of those numbers. Implement error handling to catch cases where the user enters non-numeric input.

Solution: ```python def calculate_average_from_input(): """Calculates the average of numbers entered by the user.""" try: numbers_str = input("Enter a series of numbers separated by spaces: ") numbers = [float(num) for num in numbers_str.split()] # Convert to float to handle decimals if not numbers: print("No numbers were entered.") return average = sum(numbers) / len(numbers) print(f"The average of the numbers is: {average}") except ValueError: print("Invalid input. Please enter numbers separated by spaces.") calculate_average_from_input() ```

Commentary: This program first prompts the user to enter a series of numbers. It then uses a list comprehension to convert the input string into a list of floats, handling potential `ValueError` exceptions if the user enters non-numeric input. If the list is empty, it prints a message indicating that no numbers were entered. Otherwise, it calculates and prints the average. The use of `float` allows the program to handle decimal numbers as well.

Question 3: Write a function that takes a dictionary of student names and their scores as input and returns a new dictionary containing only the students who passed (score >= 50).