TOPIC 4: Functions & Code Documentation
Completion requirements
1. What is a Function?
A function is a reusable block of code that performs a specific task. Functions allow you to organize your code, break down complex tasks, and avoid repetition. By using functions, you can make your code more modular, readable, and maintainable.
Why Functions?
- Code Reusability: Once a function is defined, it can be reused throughout the program, reducing duplication of code.
- Readability: Functions break down complex tasks into smaller, understandable pieces of code.
- Modularity: Functions allow for organizing code into logical parts, making debugging and testing easier.
Syntax for Defining a Function:
To define a function in Python, we use the def keyword, followed by the function name, parentheses (for parameters), and a colon. The code block inside the function is indented.
def function_name(parameters):
# code block
return result
- def: This keyword is used to define a function.
- function_name: The name of the function (use descriptive names to make it clear what the function does).
- parameters: The values (inputs) passed to the function when it is called. These can be optional.
- code block: The set of statements that define what the function does.
- return: The return statement is used to send a result back to the caller.
Example 1: Simple Function
This is a simple function that prints a greeting message:
def greet():
print("Hello, World!")
greet() # Output: Hello, World!
Explanation:
- The function greet() is defined with no parameters and simply prints "Hello, World!" when called.
- Calling a function: You invoke a function by writing its name followed by parentheses: greet().
Example 2: Function with Parameters
A function can take parameters (inputs), which allow it to be more flexible.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Explanation:
- The function add(a, b) takes two parameters, a and b, and returns their sum.
- The function is called with arguments 5 and 3, and the result is stored in result and printed.