Sub-programs

A subprogram is a set of instructions that performs a specific task. It can be called (used) whenever needed in a program, which helps keep the code tidy and avoids repetition.

There are two main types:

  • Procedures – do something, but don’t return a value.

  • Functions – do something and return a value.

Why use sub-programs?

Why use subprograms?

  • Makes code easier to read

  • Avoids repeating the same code

  • Makes testing easier

Subprograms are also called modules, functions, or procedures, depending on the language and context.

def add_nums():
    num1 = int(input("Enter first number"))
    num2 = int(input("Enter second number"))
    total = num1 + num2
    print("The total is", total)

# Main
add_nums()
def add_nums():
    num1 = int(input("Enter first number"))
    num2 = int(input("Enter second number"))
    total = num1 + num2
    return total

#Main
total = add_nums()
print("The total is", total)

Why return a value?

Returning a value is useful when you want to get a result from the subprogram and use it somewhere else in your program.

For example, you might want to return a total, a name, or a true/false answer.

Returning values helps:

  • Share results between parts of the program

  • Make the code more flexible and useful

  • Avoid repeating calculations or tasks