Sub-programs, also known as subroutines are self-contained blocks of code that perform a specific task within a larger program. They are designed to enhance modularity, reusability, and maintainability of code.
Subprograms are first defined within the program. Once the function has been defined it can be executing anywhere within the program by calling the function, usually be writing the subprogram name, followed parentheses.
def greeting(): #Here we define the subprogram print("hello world") greeting() #Here we call the subprogram
Subprograms can be divided into two types: functions and procedures.
What is a subprogram?
Functions
A function is a block of code that performs a specific task and returns a value after execution.
Functions return a result after execution, which can be used elsewhere in the program.Since functions return values, they can be used within expressions (e.g., mathematical calculations).
Example
def add(a, b): return a + b result = add(3, 5) # Returns 8
Procedures
A procedure (often called a subroutine) is a block of code that performs a task but does not return a value. Procedures do not return a result after execution; their primary goal is to carry out a task.
Procedures are often used for performing actions like printing, modifying global variables, or interacting with the user.
What is the difference between a function and a procedure?
The code inside a subprogram is executed when it is .
Which of the following allows code to be written and tested independently?
Advantages of subprograms - Modularity
Subprograms allow for the division of complex tasks into smaller manageable units, making the code easier to understand and maintain.
Using subprograms can improve , allowing changes in one part without affecting others.
Advantages of subprograms - Reusability
Subprograms can be reused in different parts of the program or in other programs, eliminating the need for duplicating code and saving development time.
Subprograms can help reduce code , making programs easier to maintain.
Advantages of subprograms - Abstraction
Subprograms reduce complexity by hiding the details of their implementation, allowing the programmer to focus on the high-level functionality.
Subprograms allow for , meaning that complex tasks can be simplified into a single function call.
Advantages of subprograms - Code organization
Subprograms help in organizing code into logical sections, making it easier to navigate and debug.
What is the advantage of using subprograms?
Using subprograms can lead to better of code, allowing for easier navigation and understanding.