Saturday, September 21, 2024
Google search engine
HomeLanguagesPython def Keyword

Python def Keyword

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.

Python def Keyword

 

Python def Syntax

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.

Create a def function with No Arguments

In this example, we have created a user-defined function using the def keyword. The Function simply prints the Hello as output.

Python3




def python_def_keyword():
    print("Hello")
python_def_keyword()


Output:

Hello

Create def function to find the subtraction of two Numbers

In this example, we have created a user-defined function using the def keyword. The Function name is python_def_subNumbers(). It calculates the differences between two numbers.

Python3




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


Output:

subtraction of  90  and  50  is =  40

Create def function with the first 10 prime numbers

In this example, we have created a user-defined function using the def keyword. The program defines a function called python_def_prime() using the def keyword. The function takes a single parameter n, which specifies the number of prime numbers to be printed.

Python3




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


Output:

First 10 prime numbers are:  
2
3
5
7
11
13
17
19
23
27

Create a function to find the factorial of a Number

In this example, we have created a user-defined function using the def keyword. The program defines a function called python_def_factorial() using the def keyword. The function takes a single parameter n, which represents the number whose factorial is to be calculated.

Python3




# Python program to find the
# factorial of a number
 
# Function name factorial is defined
def python_def_factorial(n):
    if n == 1:
        return n
    else:
        return n*python_def_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")
else:
    print("The factorial of", num, "is", python_def_factorial(num))


Output:

The factorial of 6 is 720

Python def keyword example with *args

This is a Python program that defines a function called python_def_keyword() using the def keyword. The function uses the special parameter *args ,which allows the function to accept an arbitrary number of arguments. Inside the function, a for loop is used to iterate over the arguments passed to the function. The loop iterates over the variable arg, which represents each argument in turn, and prints it to the console using the print() function.

Python3




def python_def_keyword(*args):
    for arg in args:
        print(arg)
python_def_keyword(1, 2, 3)
python_def_keyword('apple', 'banana', 'cherry', 'date')
python_def_keyword(True, False, True, False, True)


Output:

1
2
3
apple
banana
cherry
date
True
False
True
False
True

Python def keyword example with **kwargs

This is a Python program that defines a function called python_def_keyword() using the def keyword. The function uses the special parameter **kwargs, which allows the function to accept an arbitrary number of keyword arguments.

Inside the function, a for loop is used to iterate over the key-value pairs passed to the function. The loop iterates over the kwargs dictionary using the items() method, which returns a sequence of (key, value) tuples. For each tuple, the loop unpacks the key and value variables and prints them to the console using the print() function and string formatting.

Python3




def python_def_keyword(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
python_def_keyword(name='Alice',
                   age=25, city='New York')
python_def_keyword(country='Canada',
                   language='French', population=38000000)
python_def_keyword(color='blue',
                   shape='square', size='large', material='wood')


Output:

name: Alice
age: 25
city: New York
country: Canada
language: French
population: 38000000
color: blue
shape: square
size: large
material: wood

Passing Function as an Argument

This is a Python program that defines a function called apply_function() using the def keyword. The function takes two parameters: func, which is a function, and arg, which is an argument to be passed to func. The function then returns the result of calling func with arg. The program also defines another function called square using the def keyword. This function takes a single parameter x and returns the square of x.

After defining these functions, the program calls the apply_function function with square as the func argument and 5 as the arg argument. This means that the square function will be called with 5 as its argument, and its result will be returned by apply_function().

Python3




def apply_function(func, arg):
   return func(arg)
 
def square(x):
   return x ** 2
 
result = apply_function(square, 5)
print(result) 


Output:

25

Python def keyword example with the class

In this example, we define a python_def_keyword class with an __init__() method that takes in two arguments (name and age) and initializes two instance variables (self. name and self. age). We then define a say_hello() method that prints out a greeting with the person’s name and age.We create an instance of the python_def_keyword class called python_def_keyword1 with the name “John” and age 30. We then call the say_hello() method on the python_def_keyword1 instance.

Python3




class python_def_keyword:
    def __init__(self, name, age):
        self.name = name
        self.age = age
     
    def say_hello(self):
        print(f"Hello, my name is {self.name} " +
              f"and I am {self.age} years old.")
python_def_keyword1 = python_def_keyword("John", 30)
python_def_keyword1.say_hello() 


Output:

Hello, my name is Johnand I am 30 years old.

RELATED ARTICLES

Most Popular

Recent Comments