How to Use def () Function in Python

How to Use def () Function in Python

3 mins read2.9K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Aug 16, 2024 14:40 IST

The def () keyword in Python defines the function users can use to build their own. In this article, we will discuss using a def () keyword to create your own function in Python.

2023_01_MicrosoftTeams-image-128.jpg

In this article, we will learn how to create our own function in Python. In Python, we can create functions using def keywords.

So, without further delay, let’s move on to learn how to use a def keyword to define a function in Python.

Explore How to Find an Armstrong Number Using Python

Table of Content

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Functions in Python

Functions play an important role in any programming language. A function is a set of instructions that can be repeatedly used. In simple terms, it is a reusable piece of code that carries out a specific task. 

In Python, we mainly have three different types of functions:

  • Built-in Function
    • They are pre-defined functions that can be directly used.
    • Example: abs (), min (), max (), print (), type (), etc.
  • User Defined Function
    • They are not pre-defined functions; Python allows users to create their own functions as per their requirements.
  • Anonymous Function
    • Besides built-in and user-defined functions, Python has an anonymous function that is used without defining a name.
What is Programming What is Python
What is Data Science What is Machine Learning

How to Define and Call a Function

UserDefine Function

If you have to create a program you use repeatedly in your program, then you can define your functions. In Python, user can define their function using def keywords.

  • def keyword can be used to define the method of a class.
  • it is also used to define the member function of a class __init__().

Now, let’s see how def keyword defines a function.

Syntax

def function_name(arguments):
    “ “ “
    functions logics
    ” ” ” 
    return values

Parameters

  • def: It is a keyword that is used to define (declare) a function.
  • function_name: It is a name that you give to your function.
    • The function name should be straightforward, easily remembered, and understandable.
  • arguments: value that is passed in the function.
    • There are two special types of arguments:
      • *args: it is used when we don’t know how many arguments a function will receive during runtime.
      • **kwargs:  It is used if we want to receive named arguments
  • return: It is an optional value that returns a value from the function.
    • Function immediately exits when they come across the return statement.
    • It can be used to return multiple values.
Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Examples

Example-1: Create a function to find the cube of a number.


 
def cubic(n):
cube = n*n*n
return cube
# Using the cubic function find the cube of 3
result = cubic(3)
print(result)
Copy code

Output

27

Example-2: Create a function to find the sum of two numbers.


 
def addition(m, n):
add = m + n
print('Addition of two numbers is:', add)
# Find the sum of 9 and 10
addition(9, 10)
Copy code

Output

Addition of two numbers is: 19

Example-3: Create a function using *args


 
def addition(*args):
add = 0
for i in args:
add += i
return add
# Find the sum of first 5 integers
print('Sum of first five integers is:', addition(1, 2, 3, 4, 5))
# Find the sum of first 3 prime numbers
print('Sum of first 3 prime numbers is:', addition(2, 3, 5))
Copy code

Output

Sum of first five integers is: 15
Sum of first 3 prime numbers is: 10

Example – 4: Create a function using **kwargs


 
def roll_number(**kwargs):
for i in kwargs:
print(i, kwargs[i])
# Find the roll number and student name
roll_number(A = 1001, B = 1002, C = 1003, D = 1004, E = 1005)
Copy code

Output

A 1001
B 1002
C 1003
D 1004
E 1005

Until now, we have a clear understanding of what a Python function is and how to define one. When defining a function, we use an argument to pass the value to the function. Python allows using a user-defined function as an argument.
Confused!!
Let’s see the below example of how we can pass a function as an argument.

Passing Function as an Argument


 
def cubic(n):
return n * n * n
result = list(map(cubic, [1, 2, 3]))
print(result)
Copy code

Output

[1, 8, 27]

Conclusion

In this article, we discussed the def () keyword in Python and how to define and call a user-defined function using an example. Finally, we have discussed how a function can be passed inside another function as an argument.

Hope you will like the article.

Check Our More Python Blogs

How to Check if a Python String is a Palindrome
How to Check if a Python String is a Palindrome
A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods how to check if...read more

How to Generate Random Numbers in Python?
How to Generate Random Numbers in Python?
In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data....read more

For Loop in Python (Practice Problem) – Python Tutorial
For Loop in Python (Practice Problem) – Python Tutorial
For loops in Python are designed to repeatedly execute the code block while iterating over a sequence or an iterable object such as a list, tuple, dictionary, or set. This...read more

Calculator Program in Python: A Step-By-Step Guide
Calculator Program in Python: A Step-By-Step Guide
Looking for a powerful and user-friendly calculator program in Python? In this blog, we will discuss three different methods for calculator programs in Python. A calculator performs arithmetic operations along...read more

Conditional Statements in Python – Python Tutorial
Conditional Statements in Python – Python Tutorial
A conditional statement as the name suggests itself, is used to handle conditions in your program. These statements guide the program while making decisions based on the conditions encountered by...read more

How to Find an Armstrong Number Using Python
How to Find an Armstrong Number Using Python
Learn how to find Armstrong numbers using Python with our step-by-step guide. Discover the algorithm to identify these special numbers, which are equal to the sum of their own digits...read more

Difference Between Module and Package in Python
Difference Between Module and Package in Python
Confused with modules and packages in python, then this article is for you. This article briefly discusses the Difference Between Module and Package in Python. If you have a basic...read more

Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Difference Between Methods and Functions in Python
Difference Between Methods and Functions in Python
In Python, methods and functions have similar purposes but differ in important ways. Functions are independent blocks of code that can be called from anywhere, while methods are tied to...read more

Star Pattern in Python
Star Pattern in Python
Pattern programs in Python are a type of problem that uses nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog, we will dive...read more

Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more

Top 7 Online Python Compiler Picks for 2024
Top 7 Online Python Compiler Picks for 2024
Are you tired of installing Python on your computer? Don’t worry; we’ve got you covered with the top 7 online Python compilers for 2024! These compilers are like having a...read more

How to Compute Euclidean Distance in Python
How to Compute Euclidean Distance in Python
Euclidean Distance is one of the most used distance metrics in Machine Learning. In this article, we will discuss Euclidean Distance, how to derive formula, implementation in python and finally...read more

Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
The Bubble Sort algorithm is a simple sorting method that iterates through a given list, compares every pair of neighboring items, and exchanges them if they are out of order....read more

How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more

Types of Functions in Python
Types of Functions in Python
A function is a block of code in Python that performs a particular task. It may take zero or more inputs and may or may not return one or more...read more

Difference Between Mutable and Immutable in Python
Difference Between Mutable and Immutable in Python
Data types in Python are categorized into mutable and immutable data types. Mutable data type is those whose values can be changed, whereas immutable data type is one in which...read more

ord() and chr() Function in Python
ord() and chr() Function in Python
ord () and chr() functions of Python are built-in functions that are used to convert a character to an integer and vice-versa. In this article, we will learn how to...read more

 

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio