Function concepts in python Part 2

By

We have already explained some basic features of functions in our previous lectures.Before learn this part ,you have to learn function concepts in python part 1.

Types of Arguments:-

There are four types of arguments in python functions as given below:-

  1. Required arguments or Positional arguments.
  2. Keyword arguments
  3. Default arguments
  4. Variable Length arguments
    1.) Required arguments or Positional arguments
Required arguments must be passed in correct positional order.For example,if a function want an int, float and string to be passed it,then the call to this function should look like:
func(10,5.12,'MNT LAB')                #Correct function call
func(5.12,10,'MNT LAB')                #Incorrect function call gives error

In required arguments number of arguments passed must be match with number of arguments received.
e.g.
def func(p,r,t):
    result=p*r*t/100
    return result
p=float(input("Enter the principle amounts: "))
r=float(input("Enter the rate of interest rate:"))
t=float(input("Enter the time in year: "))
#calling the function
print("simple interest is: ",func(p,r,t))
Output:-
Enter the principle amounts: 1000.20
Enter the rate of interest rate:4.6
Enter the time in year: 5
simple interest is:  230.046
>>>
e.g.
def func(a,b,c):
    result=a+b
    print("Addition of two number is: ",result)
    print("String message is: ",c)
#calling the function
func(20,60.70,'Welcome to MNT LAB')
Output:-
Addition of two number is:  80.7
String message is:  Welcome to MNT LAB
>>>

    2.) Keyword arguments:-
  • Python allow us, this kind of function that enable us to pass the arguments in the random order.
  • Keyword arguments can be passed out of order.Python interpreter uses keywords to match the values passed with the parameters used in the function definition.
e.g.
def fun(a,b,str):
    print(a,b,str)
#funtion calling
x=fun(5,10,'val')            #valid arguments
y=fun(a=5,b=10,str='val1')   #valid arguments
z=fun(str='val2',b=10,a=5)   #valid arguments
w=fun(str='val3',a=5,b=10)   #valid arguments
Output:-
5 10 val
5 10 val1
5 10 val2
5 10 val3
>>> 
e.g.
def fun(val1,msg,val2):
    print(val1,msg,val2)
#funtion calling
fun('Ram','Welcome to MNT LAB','Shyam')
Output:-
Ram Welcome to MNT LAB Shyam
>>> 
Note:- Python allows us to provide required arguments and keyword arguments in a function at the time of function call.However the required argument must not be given after the keyword argument.It means,if the first argument starts with  keyword argument in function call then the next argument should be also the keyword arguments.Other program gets error.
e.g.
def fun1(a,b,c):
    sum=a+b+c
    return sum
#funtion calling
print("The value of first sum is =",fun1(2,b=5,c=10)) #valid arguments
print("The value of second sum is =",fun1(a=10,b=5,c=10)) #valid arguments
#print("The value of third sum is =",fun1(a=20,b=5,10))#gets error,invalid argument
Output:-
The value of first sum is = 17
The value of second sum is = 25
>>> 
    3.) Default arguments:- 
Python allows us to initialize the arguments at the function definition.If the value of any of the arguments is not provided in the function definition,then we can pass it at the time of function call.I have given a best example to understand the default arguments concepts in function.
e.g.
def sum (a,b,c=10):
    result=a+b+c
    return result
#funtion calling
print("The sum of a,b,c is=",sum(20,30))
print("The sum of a,b,c is=",sum(20,30,c=40)) #c=10 value is override with c=40
print("The sum of a,b,c is=",sum(a=20,b=30))
Output:-
The sum of a,b,c is= 60
The sum of a,b,c is= 90
The sum of a,b,c is= 60
>>> 
    4.) Variable-length arguments :-
Variable-length arguments can be used in situations where the number of arguments are not fixed.Means, sometimes we may not know the number of arguments to be passed in the project.
 We define the variable-length arguments using the *args as *<variable-name>.
e.g.
#define the function
def string(*name):
    print("The type of argument is :",type(name))
    print("Printing the name using for loop:")
    for str in name:
        print(str)
#calling the function   
string('Ram','MNT','Raj','123')
Output:-
The type of argument is : <class 'tuple'>
Printing the name using for loop:
Ram
MNT
Raj
123
>>> 
Note:- In above code,we have pasted the *name as variable-length argument.When we call the function and passed values which are treated as tuple internally. 
There are properties of python arguments as given below:-
  • Before parameter representing variable number of arguments(args) 0 or more normal positional arguments may occur.
e.g.
#define the function
def fun1(i,j,s="default string",*args):
    print()
    print(i,j,s,end='')
    for var in args:
        print(var,end='')
#function calling
fun1(20,3.14)
fun1(5,j=1.14)
fun1(j=5,i=15)
fun1(50,1.35,'Ram ','MNT LAB')
Output:-
20 3.14 default string
5 1.14 default string
15 5 default string
50 1.35 Ram MNT LAB
>>> 
  • After args only keyword arguments can occur.
e.g.
#define the function
def show(a,*args,b='!'):
    print(a,b)
    for i in args:
        print(i,b)
#function calling
show(20)
show(20,40)
show(10,20,30)
show(10,20,30,40,50,b='MNT LAB')
Output:-
20 !
20 !
40 !
10 !
20 !
30 !
10 MNT LAB
20 MNT LAB
30 MNT LAB
40 MNT LAB
50 MNT LAB
>>> 
Unpacking Arguments:- 
  • Suppose a function is expecting positional arguments and a user has passed list or tuple.In such case we need to unpack the list or tuple using * operator  before passing it to the function.
e.g.
#define the function
def display(p,q,r,s,t):
    print(p,q,r,s,t)
list1=[12,24,36,48,60]
tuple1=('Ram','Shyam','MNTLAB','Neha','Rajiv')
#function calling
display(*list1)
display(*tuple1)
Output:-
12 24 36 48 60
Ram Shyam MNTLAB Neha Rajiv
>>> 
  • Suppose a function is expecting keyword arguments and user has passed a dictionary.In such case we need to unpack the dictionary first using ** operator before passing it to the function.
e.g.
#define the function
def display(id='101',name='MNT'):
    print(id,name)
dict={'id':'102','name':'MNT LAB'}
#function calling
display(*dict)
display(**dict)
Output:-
id name
102 MNT LAB
>>> 
Note:- The first call to display() passes keys to it,whereas,the second call passes values.
Scope of Variables:-
The scope of the variables depend upon where the variable is being declared.
There are two types of scope of variable as given below:-
  1. Global variable
  2. Local variable
    1.) Global variable:- The variable defined outside the function,is known as global scope.We can access this variable within function as well as outside the function also.
e.g.
#define the function
x=200
y=500
def display():
   print("Printing the global variable inside the function= ",x,y)  
#function calling
display()
#Gives an error because local variable can't access outside the function or scope
print("Printing the global variable outside the function=",x,y
Output:-
Printing the global variable inside the function=  200 500
Printing the global variable outside the function= 200 500
>>> 
 2.) Local variable:- The variable defined in one part of the program or inside the function,is known as local scope.We can access this variable within that function or part of program.We can't access it from the outside of the program.
 e.g.
#define the functiondef display(a,b,c):
   x=a+b+c
   print("Printing the sum inside the function= ",x)
#function calling
display(10,20,30)
#Gives an error because local variable can't access outside the function or scope
print("Printing the sum outside the function=",x)
Output:-
Printing the sum inside the function=  60
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\functions.py", line 9, in <module>
    print("Printing the sum outside the function=",x)
NameError: name 'x' is not defined
>>> 
Watch Complete Lecture Video:

For More...

0 comments:

Post a Comment

Powered by Blogger.