5.1 Syntax and basics of a function (BT101CO)
In the logic of problem-solving, a Function is a self-contained block of code that performs a specific task. Functions allow you to write code once and "call" it multiple times, which follows the DRY (Don't Repeat Yourself) principle.
1. Function Syntax
To define a function in Python, you use the def keyword.
# Structure:
def function_name(parameters):
"""Docstring: Optional description of the function"""
# Body of the function (indented)
return value # Optional
def: The keyword that starts the function definition.- Function Name: A unique identifier following the same rules as variables.
- Parameters: Inputs listed inside parentheses (optional).
- Colon (
:): Marks the end of the header. - Indentation: The code block belonging to the function must be indented.
return: Sends a result back to the caller and exits the function.
2. Basic Components of a Function
Defining vs. Calling
Defining a function just stores the logic. To actually execute the code, you must "call" it by its name followed by parentheses.
# 1. Defining
def greet():
print("Hello! Welcome to Python.")
# 2. Calling
greet()
Parameters and Arguments
- Parameters: The variables listed in the function definition (the "placeholders").
- Arguments: The actual values passed to the function when it is called.
def add_numbers(a, b): # a and b are parameters
sum = a + b
print(f"The sum is: {sum}")
add_numbers(10, 20) # 10 and 20 are arguments
3. The return Statement
A function can either perform an action (like print()) or calculate a result and return it to the main program. Once a return is executed, the function stops immediately.
def multiply(x, y):
return x * y
# The returned value is stored in a variable
result = multiply(5, 4)
print(result) # Output: 20
4. Types of Functions
- Built-in Functions: Functions already provided by Python (e.g.,
print(),input(),len(),range()). - User-defined Functions: Functions created by the programmer to solve specific problems.
5. Why Use Functions?
From a "Problem Solving" perspective, functions are essential for:
- Modularity: Breaking a complex problem into smaller, manageable pieces.
- Reusability: Writing the logic once and using it across different parts of the program.
- Readability: Code is much easier to read when tasks are named clearly (e.g.,
calculate_tax()).
Summary Checklist
| Component | Required? | Purpose |
|---|---|---|
def keyword | Yes | Tells Python you are starting a function. |
Parentheses () | Yes | Holds input parameters. |
Colon : | Yes | Indicates the start of the code block. |
| Indentation | Yes | Defines the scope of the function. |
return | No | Used if you need to send a value back. |