Previous Module
Next Module

COMPUTER SYSTEMS: Encoding and compression

COMPUTER SYSTEMS: Network topologies

COMPUTER SYSTEMS: Wired and wireless networks, protocols, and layers

COMPUTER SYSTEMS: Threats to computer systems and networks

COMPUTER SYSTEMS: Operating systems and utility software

COMPUTER SYSTEMS: Impact of technology on society

ALGORITHMS AND PROGRAMMING: Types of data

ALGORITHMS AND PROGRAMMING: Producing robust programs

ALGORITHMS AND PROGRAMMING: Designing, creating, and refining algorithms

ALGORITHMS AND PROGRAMMING: Programming languages

  • Subprograms are blocks of code that can be called and reused. They make code more structured and readable. 
  • A subprogram is called by its name and passing required arguments. You can call a subprogram multiple times to avoid repeating code. 
  • There are two types of subprograms: 
    • Functions: return a value.

# Function example

def add_numbers(a, b):

total = a + b

return total

    • Procedures: perform an action but do not return a value.

# Procedure example

def def print_grade_report(name, marks):

# Calculate average

total = sum(marks)

average = total / len(marks)

 
 

# Determine grade

if average > = 80: grade = “A

elif average > = 70: grade = “B

elif average > = 60: grade = “C

elif average > = 50: grade = “D

else: grade = “F

 
 

# Print the report (no value returned)

print(“Student Name:”, name)

print(“Marks:”, marks)

print(“Average:”, average)

print(“Grade:”, grade)

 
 

# Calling the procedure for multiple students

print_grade_report(“Kai”, [85, 90, 88])

print_grade_report(“Toby”, [32, 40, 29])

print_grade_report(“Atika”, [67, 81, 73])

  • Local variables: are declared inside the subprogram and only used there.
  • Global variables: are declared outside the subprogram and are accessible anywhere.

x = 10                    # Global variable

def change_local():

x = 5                 # Local variable

print(x)

change_local()            # 5

print(x)                  # 10 (global x unchanged)

  • Arrays (lists in Python) can be passed to subprograms as parameters. The subprogram can process all elements of the array (e.g. finding totals/averages, or searching for values),

def print_average(marks):

average = sum(marks) / len(marks)

print(“Average:”, average)

student_marks = [70, 85, 90, 60]                     # Array

# Calling the procedure

print_average(student_marks)                         # Average: 76.25

Unlock Subprograms

Subscribe to SnapRevise+ to get immediate access to the rest of this resource.

Premium accounts get immediate access to this resource.

Previous Module
Next Module