Introduction
Introduction to Subprograms
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.
Functions
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
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.
Example Procedure
def greet(name): print(f"Hello, {name}!") greet("Maria") # Outputs: Hello, Maria!
Advantages
Advantages of Subprograms
1. Modularity
Subprograms allow for the division of complex tasks into smaller, manageable units. This modular approach makes the code easier to understand, test, and maintain.
2. Reusability
Subprograms can be reused in different parts of the same program or even in different programs. This eliminates code duplication and helps save development time and effort.
3. Abstraction
Subprograms reduce overall complexity by hiding the details of their internal implementation. Programmers can use them by understanding only their interface, focusing instead on higher-level logic.
4. Code Organization
Subprograms help structure code into logical sections or blocks. This organization improves readability and makes debugging, updating, and navigating the codebase more efficient.