VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/08/what-are-functions-in-python-how-to-create-functions-in-python/

⇱ What are Functions in Python and How to Create Them?


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

What are Functions in Python and How to Create Them?

Harika Last Updated : 03 Jul, 2023
7 min read

Introduction

In Python programming, functions are essential building blocks that allow us to organize and reuse code efficiently. Functions provide a way to encapsulate a set of instructions, perform specific tasks, and return results. They are crucial in modularizing code, enhancing code readability, and promoting code reusability. This article provides an insightful introduction to functions in Python, exploring their definition, types, syntax, and examples, highlighting their significance in creating well-structured and efficient programs.

This article was published as a part of the Data Science Blogathon

What are Functions in Python?

A function in programming is a block of code organized by a set of rules to accomplish a specific task. They can be reused any number of times at any point during software development.

Types of Functions in Python

Built-in functions: Every programming language has pre-defined/library functions to implement basic functionalities.

Learn more about them from our article on Python Built-in Functions.

The most frequently used function in any programming language is the print() function that prints the specified message.

It is great to have built-in functions but, what if we have a requirement that cannot be accomplished using the existing functions? We may need to create a function of our own.

The functions created by the users are called User-defined functions.

Defining a Function in Python

Below are the steps to define a function:

The function code blocks must start with the keyword def followed by the function nameparentheses( () ), and colon(:).

Anything that is inside the parentheses is the input or parameter of the function. (The values that are passed to the function are called arguments. )

After the function declaration, we can write the description using docstring (β€œβ€β€ β€œβ€β€) that help the users understand the purpose of the function.

After the docstring comes to the code related to the functionality.

Ends with a print or return statement.

Syntax to define a function:

  1. def FunctionName(parameter):
  2. β€œβ€β€ This is a test function β€œβ€β€
  3. # code to do computation to the parameter
  4. print(output)
  5. return output

Print vs Return Statements

The print() function will only print the specified message or variable given, whereas the return statement returns the message or variable to be stored into another variable when the function is called. Return statement allows us to use the output of a function.

Execution will be stopped after reaching the return statement.

You can return multiple values by separating them using commas.

Calling a Function in Python

A function can be called using its name. We must pass valid values to the parameters specified while defining the function.

Syntax to call a function:

functionName(argument)

Example Function 

To implement the addition of two numbers. We will see two functions – one with a print and the other with a return statement.

Function with a Print Statement

def print_sum(a, b):

"""This function prints the sum of two numbers"""

output = a+b

print("Sum is: ", output)

# driver code

x = print_sum(10, 2)

print("X is: ", x)

Output

Sum is: 12
X is: None

Function with a Return Statement

def return_sum(a, b):

"""This function returns the sum of two numbers"""

output = a+b

return output

# driver code

y = return_sum(-23, 8)

print("Y is: ", y)

Output

Y is: -15

If we observe both the outputs, the print statement doesn’t return the output, so we cannot store it into another variable (x). The return statement returns the output, so we can store it into another variable (y).

Here a, b are called the parameters, and -23, 8 are called the arguments of the function return_sum.

Also Read: Methods in Python – A Key Concept of Object Oriented Programming

Types of Arguments

Functions can be called by using the below types of arguments:

  1. Required arguments
  2. Optional arguments
  3. Positional arguments
  4. Keyword arguments
  5. Variable-length arguments (*args, **kwargs)

1. Required Arguments

These are the arguments that must be passed to a function. Without them, it throws an error when the function is called.

Assume we have a function that prints the given name in the Title case.

def UpperCase(name):
formatted_name = name.title()
print("Formatted name is: ",formatted_name)

# calling student function
UpperCase()
πŸ‘ Function in Python

It says the function is missing the value(argument) of the required parameter (name). To avoid such errors, we must pass a valid argument to the parameter.

UpperCase('analytics vidhya')
πŸ‘ Function in Python

2. Optional Arguments

Some function parameters take default values while defining the function. And there is no need to provide values for them which makes them optional arguments.

Assume we need a ’10’ multiplier function.

def multiplier(a, b=4):

return a * b

print("with default argument: ",multiplier(3))

print("Changing the default argument: ",multiplier(3, 6))

In line 4 of the above code, we are calling the multiplier function by passing only one value but it doesn’t throw an error because it is equivalent to function the arguments a=3, b=4 (default value).

In line 5, we are calling the function with the arguments a=3, b=6(charged the default value).

Before reading further, think of a minute and guess the output.

πŸ‘ Function in Python

3. Positional arguments

Positional arguments are the values passed to the function in the same order as the parameters specified.

Assumes we have a function that prints full name by taking the first name, middle name, and last name.

def fullname(fname, mname, lname):

print("Full Name is: ", fname + " " +mname + " " + lname)

# Main character of Harry Potter series is "Harry James Potter"

fullname('Harry', 'James', 'Potter')

Output:

πŸ‘ Python Funtions

Changing the position of arguments and calling the function.

fullname('Potter', 'Harry', 'James')
πŸ‘ Output

Now see the reaction of Harry πŸ‘‡:

So, it is important to preserve the order of the arguments. However, it would be tiresome if a function accepts more parameters.

Is there a way to not look for the order of the parameters yet passing the arguments correctly? Yes, the answer is keyword arguments.

4. Keyword Arguments

Keyword argument is where the name of the parameter is provided while passing the function arguments.

Consider the same function fullname. Calling the function using keyword arguments.

fullname(lname='Potter', fname='Harry', mname='James')
πŸ‘ Image

Without looking for the order of parameters, we can get the correct Full Name. This looks great, isn’t it?

5. Variable-length Arguments (*args, **kwargs)

*args are the non-keyword arguments/positional arguments. We can pass any number of arguments by separating them using commas or by passing a list prefixed with a * symbol (*list).

**kwargs are the keyword arguments. We can pass any number of keyword arguments directly or by using a dictionary( key, value pairs).

def variable(num1, *args, **kwargs):
 print("num1: ", num1)
 for arg in args:
 print("arg: ",arg)
 for key, value in kwargs.items():
 print("kwarg: ", value)
variable(2, 3, 4, 5, key1=6, key2=7)
πŸ‘ Image

The function β€˜variable’ has one position argument num1 (first positional argument will always be assigned to num1), two non-keyword arguments (*args), and two keywords arguments (**kwargs).

Now, let us list and dictionary to pass *args, and **kwargs

def variable(num1, *args, **kwargs):

print("num1: ", num1)

for arg in args:

print("arg: ",arg)

for key, value in kwargs_dict.items():

print("kwarg: ", key, value)

list_of_args = [4, 5]

kwargs_dict = {

'key1':6,

'key2':7

}

variable(*list_of_args, **kwargs_dict)
πŸ‘ Image

The first element of the list is assigned to num1, remaining elements are assigned to *args. The elements of the dictionary are assigned to **kwargs.

Nested Functions

The function defined inside another function is called a nested or inner function.

def mainfunction():

print("Executed Outer function")

def nestedfunction():

print('Executed Nested function')

The outer function can be called, as usual:

mainfunction()
πŸ‘ Image

Try calling the nestedfunction

πŸ‘ Image

It threw an error saying β€˜nestedfunction’ is not defined. So, we should understand that nested functions must be called inside the main function to be executed.

def mainfunction():
print("Executed Outer function")
def nestedfunction():
print('Executed Nested function')
nestedfunction()
mainfunction()

The above code executed both functions successfully.

πŸ‘ Image

Higher-order Functions

A function is said to be a higher-order function if a function is passed as an argument to it.

Assume we are building a tiny calculator. Define separate functions for addition and subtraction.

  1. def add(a, b):
  2. return a + b
  3. def sub(a, b):
  4. return a – b

define a higher function calc that takes add or sub-functions are arguments in addition to a, b.

  1. def calc(func, a, b):
  2. result = func(a, b)
  3. print(β€œResult is :”, result)

Call the calc function by passing add, sub functions as input

calc(add, 4, 6)
calc(sub, 2, 3)
πŸ‘ Image

Conclusion

In conclusion, functions in Python serve as powerful tools for organizing and managing code. They enable code reuse and modularity and improve overall program efficiency. This article has explored the definition, types, syntax, and examples of functions in Python. By effectively leveraging functions, developers can create cleaner, more maintainable code that promotes reusability and enhances readability. Whether performing specific tasks, handling complex operations, or improving code structure, functions play a pivotal role in Python programming and are fundamental to building robust and scalable applications. By mastering the art of functions, developers can unlock the full potential of Python and elevate their programming skills to the next level.

To know more about Python and its functions, consider taking up this free course on Introduction to Python!

Frequently Asked Questions

Q1. What are the 4 types of functions in Python?

A. The four types of functions in Python are built-in functions (e.g., print(), len()), user-defined functions, anonymous functions (lambda functions), and recursive functions.

Q2. What is a function in Python example?

A. An example of a function in Python is the β€œsum()” function, which takes a sequence of numbers as input and returns their sum. For example, sum([1, 2, 3]) would return 6.

Q3. How to define a function?

To define a function in Python, you use the β€œdef” keyword followed by the function name, input parameters in parentheses, and a colon. The function body is indented and contains the code that defines the function’s logic and operations.

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Hi, my name is Harika. I am a Data Engineer and I thrive on creating innovative solutions and improving user experiences. My passion lies in leveraging data to drive innovation and create meaningful impact.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner