  # Functions In python

Module - 6 Functions in Python
Functions In python

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:

• C0 is the initial investment
• C1 to Cn are the expected cash flows in periods 1 to n
• r is the discount rate

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:

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.

1. Built In functions:

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

1. Function names should be lowercase, with words separated by underscores.
2. Functions should have a descriptive title that clearly communicates the reason for the function.
3. Avoid utilizing single-letter phrases and shortened forms unless they are standard abbreviations (e.g., len() or max()).
4. Maintain a strategic distance from using underscores at the start or conclusion of the function name.
5. Avoid using special characters (e.g. !, @, #, \$, %).

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:

1. The def keyword
2. The function name
3. Parameters (optional)
4. The function body consists of one or more indented lines of Python code.

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:

1. Call by value:
``````
c= a+b
return c

``````

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.

1. Call by reference:
``````def add_ref(list):
list.append(4)

my_list = [1,2,3]

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.

1. Code Reusability: Functions allow us to reuse our code multiple times. This helps us save time and resources while coding.
2. Readability: Functions make our code more readable. By breaking our code into small chunks, we can easily understand and debug our code.
3. Abstraction: Functions provide abstraction. This means that we can hide the complexity of our code and focus on the task at hand.
4. Maintainability: With functions, we can easily maintain our code. We can modify a single function without affecting the rest of the code.
5. Testing: Functions make it easy to test our code. We can test each function separately and ensure it works properly.

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:

1. Functions are used to group code into reusable blocks.
2. Functions help avoid code duplication, making code easier to maintain and debug.
3. Function parameters can be used to pass data into a function.
4. Return values can pass information from a function back to the caller.
5. Functions can be used to create modules and libraries, allowing for code reuse.
6. Python provides built-in functions and libraries for commonly used tasks.
7. Functions can be used to define custom operations and algorithms.

Quiz:

1. What does the 'def' keyword do in Python?
1. Defines a variable
2. Defines a function
3. Defines a class
4. Defines an array

1. What does the 'return' keyword do in Python?
1. Returns a value
2. Returns a variable
3. Returns a function
4. Returns an array

1. What type of object is returned by a Python function?
1. Integer
2. String
3. Float
4. Object

1. What is the default value of a parameter in a Python function?
1. Null
2. None
3. Empty string

###### Recommended Courses
Certification in Full Stack Data Science and AI  20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters in CS: Data Science and Artificial Intelligence  20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

Related Tutorials   1444 Data Science Tutorial  1970   802   1132 GATE Data Science and AI 2024  1338

Related Articles How does Zomato use Machine Learning?  8 mins  4566 Here Is How Ai Is Changing the World of Sports Forever!  11 mins  2513 How Machine Learning is Revolutionizing Customer Credit Risk Management  5 mins  3267 Implementation of Credit Risk Using ML  9 mins  2166 How Netflix Uses ML & AI For Better Recommendation for Users  9 mins  3384 Why do we always take p-value as 5%?  7 mins  4753

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter. Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter Related Tutorials to watch  Made with  in Bengaluru, India