Saturday, July 18, 2020

Types of Function in python

In python, function can be classified into two types based on who is defining the function i.e. pre-defined function and user-defined function
per-defined function can be further classified into Built-in function and function defined in modules

function%20types.JPG

Pre-defined function

These are the function that are present already defined in the system, they are either inbuit or they are defined in some external module

Built-in function:

We have been using these function, for example print(), int(), float(), input etc. to use them we have to simply call them. example:
In [2]:
nm=input("enter your name")
print("hello ", nm)
enter your namebender
hello  bender
in the above program we have used input() and print() inbuilt function, these are already defined in python so we dont have to define or import them

Function defined in modules

These function are defined in module i.e. seperate program files and not in the program itself. import keyword has be used to get the function in calling program
syntax:
import module_name
module_name.function_name()
OR
import module_name as alias
alias.function_name()

In [4]:
import math
val=math.sqrt(25)
print(val)
5.0
In [5]:
import math as m
val=m.sqrt(64)
print(val)
8.0
here the function sqrt() is neither defined by us or nor present by default as simply calling sqrt() will through an error but this function is defined in the math module and can be imported in this script by importing the math module and calling the function by using dot operator(as dot symbolizes that sqrt belogs to math module.we will look into creating modules later

User-defined function

Now these are the function which are custome created by the user, is define in the same program and is called in the same program itself
In [7]:
def sayHello(name):
    print("Hello ", name)

sayHello("tom")
Hello  tom
Here sayHello is the user defined function. You can read all about user defined function here.
References:
1. computer science for class 12 by sumita arora
Share: