Functions in Python

This recipe explains what are functions in python

How to define and call a function in Python

In this tutorial, let us discuss how to define a function in python.

In python, we might have come across thousands of predefined functions like print(), filter(), map() etc. Python also provides us an option to write our own function which are called User defined functions. The predefined functions in python that we use are also functions that were defined by someone else and made open source so that our lives can be easy :)

Explore Interesting IoT Project Ideas for Practice

Now let us see how to write functions of our own. We can define functions using the def keyword in python as shown below


def function_name():
    #Anything that you want to do.

For example,


def hello():
    print("Welcome to ProjectPro!")    

We can call this function later in any part of the code as shown below.


    hello()

There might be cases where we want we might want to change the logic of our code depending on one or more inputs. For such cases, we can create something called arguments while defining the function. We can pass those arguments to the function during the function call.

This is how we define functions with arguments


def function_name(arg1, arg2):
    #Anything that you want to do with arg1 and arg2

Python supports two types of arguments. They are called positional and keyword arguments. Positional arguments are usually mandatory arguments that needs to be passed during a function call whereas keyword arguments are those to which we can set a default value if that argument is omitted during function call. Positional arguments are are arguments that can be called with their positions. Keyword arguments are those that are called with their argument names. Lets understand with an example


    #Function Definition
    def hello_new(username,already_a_user=False):
        if already_a_user:
            print(f"Hello {username}! Good to see you back!")
        else:
            print(f"Hello {username}! Welcome to ProjectPro!")
    
    #Function call
    hello_new("Claire") 
    # prints Hello Claire! Welcome to ProjectPro!
    hello_new("Claire", already_a_user=True) 
    # prints Hello Claire! Good to see you back!

Here, username is the positional argument and already_a_user is a keyword argument. As mentioned earlier, keyword argument can be used with their argument names.

It is always mandatory in python that while defining a function, the keyword arguments MUST follow the positional arguments.

Hurray! we have come to the end of the tutorial! Hope you enjoyed learning about functions in python :)

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Multilabel Classification Project for Predicting Shipment Modes
Multilabel Classification Project to build a machine learning model that predicts the appropriate mode of transport for each shipment, using a transport dataset with 2000 unique products. The project explores and compares four different approaches to multilabel classification, including naive independent models, classifier chains, natively multilabel models, and multilabel to multiclass approaches.

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

Predictive Analytics Project for Working Capital Optimization
In this Predictive Analytics Project, you will build a model to accurately forecast the timing of customer and supplier payments for optimizing working capital.