Definition: Functions in Python
A function in Python is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and make programs easier to read and maintain.
To define a function in Python, use the def keyword, followed by the function name, parentheses (with optional parameters), and a colon. The function body is indented.
Syntax:
``python
def function_name(parameters):
code block
return value # optional
`
Worked Example: Sum of Two Numbers
Let's create a function that adds two numbers and returns their sum.
Step 1: Define the Function
`python`
def add_numbers(a, b):
result = a + b
return result
Step 2: Call the Function
`python`
sum_result = add_numbers(3, 5)
print(sum_result)
Step 3: Mathematical Representation
The function computes:
$$ \text{add_numbers}(a, b) = a + b $$
For $a = 3$ and $b = 5$:
$$ \text{add_numbers}(3, 5) = 3 + 5 = 8 $$
Step 4: Output
The program prints:
``
8
Takeaways
- Define functions in Python using def`, a name, parameters, and an indented code block.
- Call functions by using their name and passing required arguments.
- Functions help make code modular, reusable, and easier to understand.