Overview
In Python, a function is a group of related statements that work together to complete a particular job. The partitioning of our software into smaller, modular chunks is made more accessible by using functions. As the size of our program increases, functions assist in making it more structured and manageable. Moreover, it makes the code reusable and gets rid of duplication.
What are Functions in Python?
There was a programmer named Sarah who was interested in the financial industryđ¸. She noticed that many complex calculations đ§Ž were required to analyze data and make informed decisions. She thought about how she could use her programming skills to help financial analysts đš and perform these calculations quickly and efficiently.
Sarah knew that functions in Python could help organize code into separate, reusable blocks that can perform specific actions and return a result. She remembered that the NPV formula was:
She realized that the capacity to define her functions that could be utilized numerous times in a program was remarkably adequate and might offer assistance in keeping code DRY (Don't Repeat Yourself) versatile.
She thought of how she could make a function that could assist financial analysts in calculating a venture's net present value (NPV). She remembered that the NPV formula was:
NPV = C0 + (C1 / (1 + r)^1) + (C2 / (1 + r)^2) + ... + (Cn / (1 + r)^n)
Where:
Sarah knew she could create a function called calculate_npv() that would take three arguments: the initial investment, a list of cash flows, and the discount rate. The function would then use a for loop to calculate the NPV using the above formula and return the resulting value.
Sarah was excited about the possibilities of using functions like calculate_npv() in the financial industry. She knew these functions would allow analysts to perform complex calculations quickly and efficiently. By encapsulating the calculation in a function, the analyst could reuse the code for different investments, reducing the risk of errors and saving time.
She made the below function to calculate đ§Ž the net present value by defining a user-defined function:
def calculate_npv(initial_investment, cash_flows, discount_rate):
npv = initial_investment
for i in range(len(cash_flows)):
npv += cash_flows[i] / (1 + discount_rate) ** (i+1)
return npv
In this case, the calculate_npv() function takes three arguments: the initial venture, a list of cash flows, and the discount rate. The function then uses a for loop to calculate the NPV using the abovementioned formula and returns the resulting value.
Functions like calculate_npv() are helpful in the financial industry because they allow analysts to perform complex calculations quickly and efficiently. By encapsulating the calculation in a function, the analyst can reuse the code for different investments, reducing the risk of errors and saving time.
Types of Functions in Python
1. User-Defined Functions:
User-defined functions are custom procedures that users program and implement in their software. These functions allow users to define reusable blocks of code that perform specific actions or tasks . Users can name functions, determine input parameters , and write code for the function's functionality.
These functions provide flexibility and modularity to software programs :robot:. They encapsulate common groups of actions into a single function that can be called whenever that functionality is needed. Users can build upon their functions by calling one function from within another. This helps ⨠keep programs organized , efficient, and less redundant.
Example:
Example:
def add_two_numbers(x, y):
return x + y
This code defines a user-defined function named "add_two_numbers" which takes two arguments (x and y) and returns their sum.
Built-in functions in Python are pre-defined functions that can be used without additional code. They are always available for use in any Python program and do not need to be imported or defined by the programmer. Examples of built-in functions include print(), input(), len(), str(), int(), float(), list(), tuple(), dict(), and range().
Python's wide range of built-in functions is one of the reasons why it is a popular and versatile programming language. These functions perform everyday tasks such as getting user input, printing output, determining the length of objects, converting between data types, and generating sequences. The availability of built-in functions simplifies basic tasks and makes Python easy for beginners yet powerful enough for complex projects.
Example:
print(abs(-5))
The abs() function in Python returns the absolute value of a number. In this case, the absolute value of -5 is 5.
Rules for Naming Functions in Python
Syntax of Python Functions
def name_of_function(arguments):
# body of the function
statement(s)
# calling the function
name_of_function(arguments)
This is the syntax for defining a function in Python. The 'def' keyword indicates the start of a function. Then the function's name and any arguments are in parentheses following. The function's code, with the necessary statements and commands to accomplish the task, make up the body. Finally, the function is called using its name and required arguments.
The components of a python function definition
A Python function definition consists of four main components:
The def keyword defines a function in Python. The function name follows def, then any parameters in parentheses. A colon (:) ends the definition. The function's code, indented four spaces, runs when called. Once defined, call the function anywhere by name and parameters.
How Does a Python Function Work?
Function definition and function call are the two components of a Python function. The first step in creating a function in Python is to define it by giving it a name, parameters, statements, etc. The function is then called independently in the program using its name and any optional parameters.
How to Call a Function in Python?
When calling a function in Python, its name is preceded by parentheses. Parameters are listed in parentheses if they are present. It is done in two ways:
def add_val(a,b):
c= a+b
return c
print(add_val(2,3))
Call by value is when a function is called with arguments copied into the function scope, and any changes made to the argument within the function scope do not affect the original argument. Call by reference is when a function is called with reference to an object, and any changes made to the Object within the function scope affect the original argument.
def add_ref(list):
list.append(4)
my_list = [1,2,3]
add_ref(my_list)
print(my_list)
The call-by-reference program shown in this example takes a list as a parameter and adds an element to the list. The new element is appended to the list, thus changing the original list. This is an example of call-by-reference as the original list changes, not just a single variable's value. In this example, the function references the list and modifies its contents.
Advantages of Functions in Python
Conclusion:
Python functions are blocks of reusable code that perform specific tasks, making partitioning software into smaller, modular chunks easier. They help in making the code more structured and manageable and eliminate duplication. In finance, Python functions perform complex calculations quickly and efficiently, such as calculating the net present value (NPV) for different investments. Python has two types of functions, namely user-defined functions and built-in functions, and it follows a set of rules for naming functions.
Key Takeaways:
Quiz:
Answer: b. Defines a function
Answer: a. Returns a value
Answer: d. Object
Answer: c. None
Related Tutorials to watch
Top Articles toRead
Read