Python Core



Admission Enquiry Form


Functions in python

Function is some set of statements which executes when it is called and perform a task. We can call them again and again in the program when we require.

OR

Function is a named block which can be reused when we require it.So, we can say that it is reusability of code.It is defined using def keyword

 

Example of function

def msg():
    print("I, am a function")

msg() # calling of function



Output

I, am a function



Calling and called function

Calling Function

The function who calls the other function is called calling function.

Called Function

The function which is being called by the calling function is a called function.





Types of functions

Built-in functions

Functions which are already defined in the python language functions library. print(), input() etc. are the built-in functions

User defined functions

Function which are defined by the user.




User defined functions:



sum() function for adding two numbers

def sum():
    n1=10
    n2=20
    res=n1+n2
    print("The sum is ",res)

sum()



Output

The sum is 30


sum() function of adding two numbers taking input from user

def sum():
    n1=int(input("Enter first number"))
    n2=int(input("Enter second number"))
    res=n1+n2
    print("The sum is ",res)

sum() #calling sum function



Arguments

A value given to the called function from where it is being called.

sum() function with arguments

sum() function for adding two numbers getting two integer arguments from where it is being called

def sum(n1,n2):
    res=n1+n2
    print("The sum is ",res)

sum(10,20)


Output

The sum is 30


Example of getting string argument

def getMessage(msg):
    print(msg)

getMessage("Welcome to compuhelp")


Output

Welcome to compuhelp



Keyword arguments

In keyword arguments the sending and cathing position of the arguments does not matter. In this we pass aguments using key=value syntax.

def item(name,price):
    print("The name of item is = "+name)
    print("The price of item is = ",price)

item(price=10,name="kitkat")


Output:

The name of item is = kitkat
The price of item is = 10



Default arguments

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default values indicate that the function argument will take that value if no argument value is passed during the function call.

def sum(n1=100,n2=200):
    res=n1+n2
    print("The sum is",res)

sum(10,20)


Output

The sum is 30



Default arguments without passing arguments

def sum(n1=100,n2=200):
    res=n1+n2
    print("The sum is",res)

sum()




Output

The sum is 300