Advanced Programming I - SSS 3 Digital Technologies note
ADVANCED PROGRAMMING I
Subject: Digital Technologies
Class: SSS 3
Term: First Term
Week: 2
Topic: Advanced Programming I
Duration: 80 Minutes (Double Period)
1. Introduction
Programming is the process of writing instructions that a computer follows to perform specific tasks. As programs become larger and more complex, programmers need ways to organise instructions, reuse code and manage collections of data efficiently.
In earlier programming lessons, students learned about variables, data types, operators, input, output and control structures. Advanced programming builds on these concepts by introducing functions, parameters, return values, arrays and lists.
These concepts help programmers develop programs that are easier to understand, test, maintain and expand.
2. Functions in Programming
2.1 Meaning of a Function
For example, a school application may need to calculate students' average scores several times. Instead of writing the calculation repeatedly, a programmer can create a function that performs the calculation whenever it is called.
2.2 Importance of Functions
Functions are useful for the following reasons:
- Code reuse: A function can be called many times without rewriting its instructions.
- Organisation: Functions divide a large program into smaller, manageable parts.
- Readability: Meaningful function names make programs easier to understand.
- Testing and debugging: Individual functions can be tested to identify errors more easily.
- Maintenance: A change to a function can improve every part of the program that uses it.
2.3 Creating and Calling a Function
The following example uses Python to define a function that displays a greeting.
def greet():
print("Welcome to Digital Technologies!")
greet()
Explanation:
defis the Python keyword used to define a function.greetis the function name.- The parentheses
()contain the parameters, if any. - The indented statement is the body of the function.
greet()calls the function and causes its instruction to run.
Output:
Welcome to Digital Technologies!
3. Parameters and Arguments
3.1 Meaning of Parameters
Parameters allow a function to work with different values rather than being limited to fixed data.
Consider this Python example:
def greet_student(name):
print("Welcome,", name)
greet_student("Ada")
greet_student("Chidi")
Output:
Welcome, Ada
Welcome, Chidi
In this example, name is the parameter. The values "Ada" and "Chidi" are arguments supplied when the function is called.
3.2 Difference Between Parameters and Arguments
| Parameter | Argument |
|---|---|
| A variable listed in a function definition. | A value or expression supplied when calling a function. |
| Receives the supplied data. | Provides the data to the function. |
Example: number in def square(number): |
Example: 5 in square(5) |
3.3 Functions with More Than One Parameter
A function may accept two or more parameters. For example, a function can add two numbers.
def add_numbers(a, b):
print(a + b)
add_numbers(10, 5)
add_numbers(20, 8)
Output:
15
28
Here, a and b are parameters. The arguments supplied in each function call are assigned to these parameters in their corresponding positions.
4. Return Values
4.1 Meaning of a Return Value
In Python, the return statement is used to send a result back to the caller. A returned value can be stored in a variable, displayed, or used in another calculation.
4.2 Example of a Function with a Return Value
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)
Output:
20
Explanation:
- The function
multiplyaccepts two parameters,aandb. - The expression
a * bmultiplies the two values. - The
returnstatement sends the product back to the caller. - The returned value is stored in the variable
result. - The
print()statement displays the result.
4.3 Difference Between print() and return
| print() | return |
|---|---|
| Displays information on the screen. | Sends a value back to the caller. |
| Displaying a value does not automatically make it available as the function's result. | The returned value can be stored or used in another expression. |
Example: print(a + b) |
Example: return a + b |
None by default. A function can display a result using print(), return a result using return, or do both.
4.4 Practical Example: Calculating a Student's Average
def calculate_average(score1, score2, score3):
average = (score1 + score2 + score3) / 3
return average
student_average = calculate_average(70, 80, 90)
print("Average score:", student_average)
Output:
Average score: 80.0
This example demonstrates how a function can accept several values, process them and return a result for use elsewhere in a program.
5. Arrays and Lists
5.1 Meaning of an Array
Arrays are useful when a program needs to manage related data such as students' scores, daily temperatures or product prices.
For example, rather than creating separate variables for five scores, a program can store them together in an array-like structure.
scores = [65, 72, 80, 91, 76]
The example above uses a Python list. Lists are commonly used for collections of values in Python and can hold values of different data types. In some other programming languages, arrays have stricter rules about the types of values they store.
5.2 Meaning of a List
Example:
subjects = ["English", "Mathematics", "Biology", "Physics"]
print(subjects)
Output:
['English', 'Mathematics', 'Biology', 'Physics']
Lists are useful for storing collections of related information, including names, subjects, prices and examination scores.
5.3 Difference Between Arrays and Lists
| Arrays | Lists |
|---|---|
| Often store elements of the same data type in conventional array implementations. | Python lists can store items of different data types. |
| Rules and available operations depend on the programming language and array implementation. | Python provides built-in operations for adding, removing and rearranging items. |
| Commonly used for structured collections of values. | Commonly used for flexible collections of items in Python. |
[10, 20, 30] create a list, not a traditional fixed-type array. Python also provides array modules and third-party libraries for other array implementations.
6. Accessing Elements in a List
Each item in a Python list has a position called an index. Python uses zero-based indexing, which means the first item is at index 0, the second at index 1, and so on.
fruits = ["Mango", "Orange", "Banana", "Pawpaw"]
print(fruits[0])
print(fruits[2])
Output:
Mango
Banana
Python also supports negative indexing. For example, fruits[-1] refers to the last item in the list.
| Index | Element |
|---|---|
| 0 | Mango |
| 1 | Orange |
| 2 | Banana |
| 3 | Pawpaw |
IndexError in Python.
7. Creating and Manipulating Lists
List manipulation means performing operations that change, organise or retrieve items in a list.
7.1 Adding Items
The append() method adds an item to the end of a list.
subjects = ["English", "Mathematics"]
subjects.append("Computer Studies")
print(subjects)
Output:
['English', 'Mathematics', 'Computer Studies']
7.2 Inserting Items
The insert() method adds an item at a specified index.
numbers = [10, 30, 40]
numbers.insert(1, 20)
print(numbers)
Output:
[10, 20, 30, 40]
7.3 Removing Items
The remove() method removes the first matching value from a list.
colours = ["Red", "Blue", "Green"]
colours.remove("Blue")
print(colours)
Output:
['Red', 'Green']
7.4 Updating an Item
An existing list item can be changed by assigning a new value to its index.
scores = [50, 60, 70]
scores[1] = 85
print(scores)
Output:
[50, 85, 70]
7.5 Finding the Number of Items
The Python len() function returns the number of items in a list.
students = ["Ada", "Bola", "Chidi", "Emeka"]
print(len(students))
Output:
4
7.6 Looping Through a List
A loop can process each item in a list without requiring a separate instruction for every item.
subjects = ["English", "Mathematics", "Biology"]
for subject in subjects:
print(subject)
Output:
English
Mathematics
Biology
8. Using Functions with Lists
Functions can receive lists as arguments and process their contents. This combines the benefits of reusable code and organised data storage.
Example: Calculating the Total of Scores
def calculate_total(scores):
total = 0
for score in scores:
total = total + score
return total
student_scores = [65, 75, 80, 90]
result = calculate_total(student_scores)
print("Total score:", result)
Output:
Total score: 310
Explanation:
- The function
calculate_total()receives a list of scores. - The variable
totalstarts at zero. - The
forloop visits each score in the list. - Each score is added to
total. - The function returns the final total.
Example: Finding the Highest Score
def highest_score(scores):
return max(scores)
marks = [45, 88, 67, 92, 74]
print("Highest score:", highest_score(marks))
Output:
Highest score: 92
9. Common Programming Errors
| Error | Explanation | Prevention |
|---|---|---|
| Incorrect indentation | Python uses indentation to identify the body of a function or loop. | Indent statements consistently. |
| Misspelt function name | The program may report that a function is not defined. | Use the same function name when defining and calling it. |
| Missing argument | A function call may supply fewer arguments than required. | Check the function definition and the supplied arguments. |
| Incorrect list index | An index may refer to an item that does not exist. | Remember that Python list indexing starts at zero. |
| Confusing print and return | A displayed value is not automatically returned by a function. | Use return when a calling expression needs the result. |
| Incorrect list method | A method may be used incorrectly or with an invalid value. | Understand the purpose of each list method and test the program. |
10. Class Activity
Activity 1: Creating a Function
Write a Python function named square_number() that accepts one number and returns its square. Call the function with the value 6 and display the result.
Activity 2: Manipulating a List
Create a list containing the names of five subjects offered in your school. Perform the following operations:
- Display the complete list.
- Add another subject using
append(). - Change one subject using its index.
- Remove one subject using
remove(). - Display the total number of items using
len().
Activity 3: Processing Scores
Create a function that accepts a list of students' scores and returns their total. Test the function with at least four scores.
11. Summary
In this lesson, we studied the basic concepts of advanced programming, including functions, parameters, arguments, return values, arrays and lists.
- A function is a reusable block of code designed to perform a particular task.
- Parameters receive data, while arguments are the values supplied during a function call.
- The
returnstatement sends a result back to the caller. - Arrays and lists store collections of values.
- Python lists use zero-based indexing.
- List methods such as
append(),insert()andremove()help manipulate list items. - Functions and lists can work together to process data efficiently.
12. Evaluation Questions
- Define a function in programming.
- State four advantages of using functions.
- Differentiate between a parameter and an argument.
- Explain the purpose of the
returnstatement. - State three differences between arrays and Python lists.
- What is zero-based indexing?
- Explain the uses of
append(),insert()andremove(). - Write a Python function that accepts two numbers and returns their sum.
13. Assignment
- Write a Python function named
calculate_area()that accepts the length and width of a rectangle and returns its area. - Create a list containing six numbers. Display the first and last items.
- Write a program that adds a new item to a list, changes an existing item and removes another item.
- Write a function that accepts a list of five examination scores and returns their average.
- Explain three ways functions and lists can be used together in real-life applications.
14. Interactive Quiz
Answer all five questions and click Submit Quiz to check your score.
Comments
Post a Comment