Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python def Keyword



The Python def keyword is used to create a function. A function is a set of statements within a block which returns specific task. The def keyword is followed by the function-name and the parenthesized list of parameters and colon[:] . The block of code should start from next line.

The def keyword is a case-sensitive. For an example, is and Is both are different.

The def keyword can be used inside the class, conditional statements. When we define a function using def keyword inside a class it is known as method.

To execute the function, which was created using def keyword we just need to call using function-name.

Syntax

Following is the syntax of the Python def keyword −

def Functionname(parameters):
                statement1
				statement2

Example

Following is a basic example of the Python def keyword −

def Tp():
    print("Welcome to Tutorialspoint")
Tp()

Output

Following is the output of the above code −

Welcome to Tutorialspoint

Using 'def' with parameters

A function which was created using def keyword, we can also accept the parameters.

Example

Here, we have defined a function with def keyword and the function named mul(). This function accepted two parameters and returned the product of the given parameters −

def mul(a,b):
    return a*b  
    
var1 = 19
var2 = 20
Mul = mul(var1, var2)   
print("Product of var1 and var2 :",Mul)

Output

Following is the output of the above code −

Product of var1 and var2 : 380

Using 'def' Keyword in class

When we use the def keyword inside the class, it defines a method. The only difference between the function and method is, functions are defined outside the class. Whereas, methods are defined inside the class.

Example

In the following example, we had created a class, Operations which contained two methods called add() and sub(). And we had created an object, Obj1 and called the methos of the class to perform various operations −

class Operations:
    def add(self,a,b):
        return a + b
    
    def sub(self,a,b):
        return a - b
        
Obj1 = Operations()
var1 = 100
var2 = 15
result_1 = Obj1.add(var1, var2)
result_2 = Obj1.sub(var1, var2)
print("Addition :", result_1)
print("Subtraction :", result_2)

Output

Following is the output of the above code −

Addition : 115
Subtraction : 85

Using 'def' Keyword in Recursion

The def keyword is used in recursion. A function which calls itself is known as recursion.

Example

def recur_fact(n):
   if n == 1:
       return n
   else:
       return n*recur_fact(n-1)
       
var1 = 5
result_1 = recur_fact(var1)
print("The factorial of", var1,":", result_1)

Output

Following is the output of the above code −

The factorial of 5 : 120  
python_keywords.htm
Advertisements