Python Function

Declaring and Invoking Functions in Python.

Function is a block of reusable code that performs a specific task.

Python - Function Calling:

Functions are defined using the def keyword, followed by the function name and a pair of parentheses containing any parameters the function takes. Here's the general syntax of a function in Python:

def function_name(parameters):
    """docstring"""
    # code block
    return value

Break down the components:

1. def: This keyword is used to define a function.

2. function_name: This is the name of the function. You can choose any valid name for your function, but it's best to choose a descriptive name that reflects what the function does.

3. parameters: These are optional inputs that you can pass to the function. If the function doesn't take any parameters, you can leave the parentheses empty. If there are multiple parameters, they are separated by commas.

4. docstring (optional): This is an optional documentation string enclosed in triple quotes ("""). It provides information about what the function does. Docstrings are useful for documenting your code and can be accessed using the 'help()' function.

5. code block: This is the block of code that defines what the function does. It can contain any valid Python code, including conditional statements, loops, and other function calls.

6. return statement (optional): This statement is used to specify the value that the function should return when it's called. If the function doesn't explicitly return a value, it returns 'None' by default. The 'return' statement is optional, and a function can have multiple return statements or none at all.

Here's an example of a simple function that adds two numbers and returns the result:

def add_numbers(x, y):
    """This function adds two numbers."""
    return x + y

You can call this function by passing two arguments and assigning the result to a variable or using it directly in an expression:

Here's an example of a simple function that adds two numbers and returns the result:

result = add_numbers(3, 5)
print(result)

Use the 'add_numbers' function to add two numbers and print the result.

PDF Copy Code
# Python function calling
def add_numbers(x, y):
    """This function adds two numbers."""
    return x + y

result = add_numbers(3, 5)
print(result)
Output:
8

Note: Functions are fundamental in Python programming as they allow you to organize your code into reusable blocks, making it easier to maintain, debug, and understand.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.