Defining and Calling 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 improve readability.
To define a function, use the def keyword, followed by the function name, parentheses (possibly with parameters), and a colon. The function body is indented. To call (execute) a function, use its name followed by parentheses, passing any required arguments.
Syntax
``python
def function_name(parameters):
code block
return result # optional
`
Example: Function to Add Two Numbers
Let's define a function that adds two numbers and returns the result.
#### Step 1: Define the Function
`python`
def add_numbers(a, b):
sum = a + b
return sum
#### Step 2: Call the Function
`python`
result = add_numbers(3, 5)
print(result)
#### Step 3: Math Behind the Example
If $a = 3$ and $b = 5$:
$$ \text{\sum} = a + b = 3 + 5 = 8 $$
So, print(result) outputs:
``
8
Takeaways
- Define functions in Python using def`, a name, parameters, and an indented code block.
- Call functions by writing their name and passing arguments in parentheses.
- Functions help make code modular, reusable, and easier to understand.