Skip to content
Related Articles
Open in App
Not now

Related Articles

Python def Keyword

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 29 Sep, 2021
Improve Article
Save Article

Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In python def keyword is the most used keyword.


def function_name: 
    function definition statements...

Use of def keyword:

  • In the case of classes, the def keyword is used for defining the methods of a class.
  • def keyword is also required to define the special member function of a class like __init__().

The possible practical application is that it provides the feature of code reusability rather than writing the piece of code again and again we can define a function and write the code inside the function with the help of the def keyword. It will be more clear in the illustrated example given below. There can possibly be many applications of def depending upon the use cases. 

Example 1: Use of def keyword.

In this example, we are going to create a user define a function using def keyword.


# Python3 code to demonstrate
# def keyword
# function for subtraction of 2 numbers.
def subNumbers(x, y):
    return (x-y)
# main code
a = 90
b = 50
# finding subtraction
result = subNumbers(a, b)
# print statement
print("subtraction of ", a, " and ", b, " is = ", result)


subtraction of  90  and  50  is =  40

Example 2: User defines a function with first 10 prime numbers.  


# Python program to print first 10
# prime numbers
# A function name prime is defined
# using def
def prime(n):
    x = 1
    count = 0
    while count < n:
        for d in range(2, x, 1):
            if x % d == 0:
                x += 1
            x += 1
            count += 1
# Driver Code
n = 10
# print statement
print("First 10 prime numbers are:  ")


First 10 prime numbers are:  

 Example 3: User defines a function with a factorial number.


# Python program to find the
# factorial of a number
# Function name factorial is defined
def factorial(n):
    if n == 1:
        return n
        return n*factorial(n-1)
# Main code
num = 6
# check is the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
    print("The factorial of", num, "is", factorial(num))


The factorial of 6 is 720

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!