Function
Introduction
A function is a group of statement bind together to make a single unit for the purpose of doing a specific task. We may execute it by calling it in the program anywhere.
Advantages of function :
- Cope-up with complexity
- Hiding details – Abstraction
- Fewer lines of code - lessor scope for bugs
- Increase program readability
- Re-usability of the code
Defining and calling function:
In python, a function may be declared as:
def function_name([Parameter list]) :
“ ” ” Doc-string i.e. documentation of the function ” ” ”
Body of the function
return value
Remember:
Implicitly, Python returns None, which is also a built-in, immutable data type.
Example:
>>> def f(a,b):
c=a+b
return c
>>> f(10, 20)
def is a keyword
f is the name of the function
a, b parameter of the function
return is a keyword
Functions can be categorized in three types:
1. Built-in function
2. Modules
3. User-defined
Built-in Functions:
- These are pre-defined functions that are already available in Python. We need to call them to use.
- We don’t have to import any module (file) for using them.
- Python has many built-in functions that makes our program easy, fast and efficient.
- Example of some built-in functions are :
int(), str(), float(), eval(), input(), min(), max(), abs(),
type(), len(), round(), range(), dir(), help()
Modules:
- Module in Python is a file (name.py) which contains the definition of variables and functions. We may divide a program into modules, then each module contains some variable and functions.
- A module may be used in other programs.
- We can use any module in the following ways
import <module-name>
from <module-name> import <function-name>
Some well-known modules are : math, random, matplotlib, numpy, pandas
User-defined Functions:
- UDFs are the functions which are created by the user as per requirement.
- After creating them, we can call them in any part of the program.
- We use ‘def’ keyword to declare a user-defined function.
Example:
#Demo of making function def f1(): print('Hello') def f2(): f1() print('Bye') #calling of the function f1() f2()
OUTPUT:
Hello
Hello
Bye
1. Function without parameter and without return value
# Example1.py
# A function without parameter and without return value
def calArea():
L=int(input('Enter length of the rectangle :'))
B=int(input('Enter breadth of the rectangle :'))
area=L*B
print('The area is ',area)
#main-program
calArea()
OUTPUT:
Enter length of the rectangle :10
Enter breadth of the rectangle :15
The area is 150
2. Function with parameter and without return value
# Example2.py # A function with parameter and without return value def calArea(L, B): area=L*B print('The area is ',area) #main-program length=int(input('Enter length of the rectangle :')) breadth=int(input('Enter breadth of the rectangle :')) calArea(length, breadth)
OUTPUT:Enter length of the rectangle :20 Enter breadth of the rectangle :10 The area is 200
3. Function with parameter and with return value
# Example3.py # A function with parameter and with return value def calArea(L, B): area=L*B return area #main-program length=int(input('Enter length of the rectangle :')) breadth=int(input('Enter breadth of the rectangle :')) ar=calArea(length, breadth) print('The area is ',ar)OUTPUT:Enter length of the rectangle :10 Enter breadth of the rectangle :30 The area is 300
4. Function with parameter and with return value more than one
# Example4.py # A function with parameter and with return value more than one def cal_arpr(L, B): area=L*B perimeter=2*(L+B) return area, perimeter #main-program length=int(input('Enter length of the rectangle :')) breadth=int(input('Enter breadth of the rectangle :')) A, P =cal_arpr(length, breadth) print('The area is ',A) print('The perimeter is ',P)OUTPUT:Enter length of the rectangle :20 Enter breadth of the rectangle :30 The area is 600 The perimeter is 100
# Example5.py # A function with parameter and with return value more than one def calculator(a,b): sm=a+b dif=a-b mul=a*b div=a/b return sm, dif, mul, div #main-program print('This program accepts two numbers and perform basic maths functions') p=int(input('Enter first number :')) q=int(input('Enter second number :')) w,x,y,z=calculator(p,q) print('The sum of',p,'and',q,'is',w) print('The difference',p,'and',q,'is',x) print('The multiplication of',p,'and',q,'is',y) print('The division of',p,'and',q,'is',z)OUTPUT:This program accepts two numbers and perform basic maths functions Enter first number :30 Enter second number :10 The sum of 30 and 10 is 40 The difference 30 and 10 is 20 The multiplication of 30 and 10 is 300 The division of 30 and 10 is 3.0
# Example6.py # A function with parameter and with return value more than one def calculator(a,b): sm=a+b dif=a-b mul=a*b div=a/b return sm, dif, mul, div #main-program print('This program accepts two numbers and perform basic maths functions') p=int(input('Enter first number :')) q=int(input('Enter second number :')) t=calculator(p,q) # See here a tuple is returned print('The sum of',p,'and',q,'is',t[0]) print('The difference',p,'and',q,'is',t[1]) print('The multiplication of',p,'and',q,'is',t[2]) print('The division of',p,'and',q,'is',t[3])OUTPUT:This program accepts two numbers and perform basic maths functions Enter first number :15 Enter second number :10 The sum of 15 and 10 is 25 The difference 15 and 10 is 5 The multiplication of 15 and 10 is 150 The division of 15 and 10 is 1.5
Actual and Formal Parameter/ Argument
The parameter which appear in function definition are known as Formal Parameter,whereas the parameter which appear in function call statement are known as Actual Parameter.
Example:
def findSum(a, b): # Here a, b are formal parameter print(‘The sum is ‘,(a+b))
#main-program X=10 Y=30 findSum(X, Y) # Here X, Y are actual parameter/ argument
OUTPUT:
The sum is 40
Variable Scope
Scope of variable means the part of program where the variable will be visible. It means where we can use this variable. • We can say that scope is the collection of variables and their values. • Scope can of two types - • Global (module) – All those names which are assigned at top level in module or directly assigned in interpreter. • Local (function) – Those variables which are assigned within a loop of function.
or
in other words:
Local variable – accessible only inside the functional block where it is declared.
Global variable – variable which is accessible among whole program using global keyword.
Non local variable – accessible in nesting of functions,using nonlocal keyword.
Example:
Local variable program: def fun(): s = "I love India!" #local variable print(s) s = "I love World!" fun() print(s) Output: I love India! I love World!Global variable program: def fun(): global s #accessing/making global variable for fun() print(s) s = "I love India!“ #changing global variable’s value print(s) s = "I love world!" fun() print(s) Output: I love world! I love India! I love India!Mutable/ Immutable behavior
Function’s behavior is different when assigning/passing to a list element /slice Python looks up for the name, from inner most scope outwards,until the name is found.
Types of arguments
Python supports four types of arguments: 1.Positional Arguments 2.Default Arguments 3.Keyword Arguments 4.Variable Length Arguments
1. Positional Arguments:
Positional arguments are arguments passed to function in correct positional order. If we change the position of their order, then the result will be changed. If we change the number of arguments, then it will result in an error.>>> def subtract(a, b): print(a -b) >>> subtract(25, 10) 15 >>> subtract(10, 25)
-15
2. Default Arguments:
To provide default values to positional arguments, we use default arguments. If we are not passing any value, then only default values will be considered. Remember that if we are passing default arguments, then we should not take non-default arguments, otherwise it will result in an error.
# Example7.py # Demo of Default Arguments def findSum(a=30, b=20, c=10): print('Sum is ',(a+b+c)) ''' def mySum(a=30, b=20, c): #Error that non-default argument follows default arguments print('Sum is ',(a+b+c)) ''' #main-program p=100 q=200 r=300 findSum(p,q,r) #output - Sum is 600 findSum(p,q) #output - Sum is 310 findSum(r) #output - Sum is 330 findSum(q,r) #output - Sum is 510 findSum() #output - Sum is 60
3. Keyword Arguments:
If a function has many arguments and we want to change the sequence of them, then we may use their name instead of their position. Thus, using keyword arguments, we can pass arguments value by keyword, i.e. by parameter name.
Precautions:
Keyword argument is easier as we do not need to remember the order. We can use both positional and keyword arguments simultaneously. But first we have to take positional argument and then the keyword argument, otherwise it will generate a syntax error. Only those parameters which are at the end of the list can be given default value. We can not have a parameter on the left with default argument value without assigning default values to parameters lying on its right side.
# Example8.py # Demo of Keyword Arguments def print_details(kvname, roname): print(kvname,'comes under',roname,'region') #main-program print_details(kvname='BSF DABLA', roname='Jaipur') print_details(roname='Jaipur', kvname='Jaisalmer AFS') print_details(kvname='Pokran', roname='Jaipur')OUTPUT:
BSF DABLA comes under Jaipur region Jaisalmer AFS comes under Jaipur region Pokran comes under Jaipur region
4. Variable length Arguments
As the name suggests, in certain situations, we can pass variable number of arguments to a function. Such types of arguments are called variable length argument. They are declared with * (asterisk) symbol in Python
# Example10.py # Demo of Variable Length arguments def findSum(*n): sm=0 for i in n: sm=sm+i print('Sum is ',sm) #main-program findSum() findSum(10) findSum(10,20) findSum(10,20,30)Passing different data structures
Passing Strings to function :
# Example11.py # Demo of Passing string to function def countVowel(s): vow='AEIOUaeiou' ctr=0 for ch in s: if ch in vow: ctr=ctr+1 print('Number of vowels in',s,'are',ctr) #main-program data=input('Enter a word to count vowels :') countVowel(data)OUTPUT:Enter a word to count vowels :E Number of vowels in E are 1
Passing List to function :
# Example12.py # Demo of Passing list to function def calAverage(L): sm=0 for i in range(len(L)): sm=sm+L[i] av=sm/len(L) return av #main-program marks=[] for i in range(5): m=int(input('Enter marks :')) marks.append(m) print('Inputted marks are :',marks) avg=calAverage(marks) print('The average is', avg)
OUTPUT:
Enter marks :95 Enter marks :96 Enter marks :97 Enter marks :98 Enter marks :99 Inputted marks are : [95, 96, 97, 98, 99] The average is 97.0
Passing Tuples to function :
''' Example13.py Demo of Passing tuple to functionQ. Write a function midPoint() which accept two points of 2-D and return the midpoint of them.For example mid-point of (2, 4) and (6, 6) is (4, 5). Use the function in main-program to test your Python code on the above values. '''def midPoint(t1,t2): m=((t1[0]+t2[0])/2.0, (t1[1]+t2[1])/2.0) return m #main-program p1=(2,4) p2=(6,6) mp=midPoint(p1,p2) print('The Mid-Point of ',p1,'and',p2,'is',mp)
OUTPUT:The Mid-Point of (2, 4) and (6, 6) is (4.0, 5.0)
Passing Dictionary to function :
''' Example14.py Demo of Passing dictionary to function ''' def printMe(d): """This function prints the values of given dictionary""" for key in d: print(d[key]) #main-program d={1:'monday', 2:'tuesday', 3:'wednesday', 4:'thursday', 5:'friday', 6:'saturday', 7:'sunday' } printMe(d)OUTPUT:monday tuesday wednesday thursday friday saturday sunday
Concept of main() in python
Including a main() in Python is not mandatory. It can structure our program in a logical way that puts the most important components of the program into one function. For non-Python programmers, we can use it in the Python code as follows:
Example15.py Demo of main() in Python Q. Find the mid-point and distance between the two points (2,6) and (4,6) ''' import math as m def midPoint(t1,t2): m=((t1[0]+t2[0])/2.0, (t1[1]+t2[1])/2.0) return m def findDistance(t1, t2): d=m.sqrt(m.pow(t2[1]-t1[1],2)+m.pow(t2[0]-t1[0],2)) return d def main(): #main-function p1=(2,4) p2=(6,6) mp=midPoint(p1,p2) print('The Mid-Point of ',p1,'and',p2,'is',mp) dis=findDistance(p1, p2) print('The distance between',p1,'and',p2,'is',dis) #calling of main() main()
OUTPUT:
The Mid-Point of (2, 4) and (6, 6) is (4.0, 5.0) The distance between (2, 4) and (6, 6) is 4.47213595499958
Type of functions on return value
Depending on return values, the three types of functions are :
Computational Function: are those function, which accept some value as argument and return different values. For example sqrt(), pow() etc.
Procedural Function: are those function which does not return any return value. They do only some task without returning any value.
For example:
def printMe(): print(‘Good morning’)
When we call printMe(), it will print ‘Good morning’ only.
Manipulative Function: are those function, which accept some value as argument and return success or failure code. Generally value 0 is returned as successful value, any other number denotes unsuccessful.
For example:
def myfunction(N): if N%2==0: return 0 else: return 1
This function is returning 0, if the number is even, otherwise it is returning 1.
Functions using Libraries
Mathematical Function
Mathematical functions are available in math module. We need to import math module in our program in order to use these functions.
To use sqrt() of this library, we shall give the following commands:
>>> import math >>> math.sqrt(16)# will print 4.0
Use >>> dir(math) <enter> command to see all variables and functions available in the math module.
String Function
String functions are available in standard module. We need not to import any other module in order to use these functions.
Example 1:
>>> s=‘kv phulera’ >>> s=s.upper() >>> print (s) >>> KV PHULERA
Example 2:
#Program to count lower, upper and digits in a string def count(s): L=0 U=0 D=0 for ch in s: if ch.islower(): L=L+1 elif ch.isupper(): U=U+1 elif ch.isdigit(): D=D+1 else: pass print('Lower case letters ',L) print('Upper case letters ',U) print('Digits ',D) #calling-of-function count('INDIA-2020') count('nCovid-2019') count('KV PHULERA')OUTPUT:Lower case letters 0 Upper case letters 5 Digits 4 Lower case letters 5 Upper case letters 1 Digits 4 Lower case letters 0 Upper case letters 7 Digits 0************************Quiz Assignment -1
No comments:
Post a Comment