Tuesday, 3 December 2019

Formal and actual parameters


Formal and actual parameters

def  f1(a,b):
 …..
 …..
#Function call
f1(10,20)

Here a,b are formal parameters, where as 10,20 are actual parameters (arguments)
There are 4 types of actual parameters are allowed in Python
1.     Positional arguments
2.     Keyword arguments
3.     Default arguments
4.     Variable length arguments
Positional Arguments:
#example program on positional arguments
def add(a,b):
    c=a+b
    print(c)
add(10,6) #positional arguments
add(2,3)
"""output:
16
5
>>>
"""

The number of arguments and position of arguments must be matched. If we change the order then result may be changed. If we change the no of arguments then we will bet error.
Parameters passed to a function in correct positional order.

2.  keyword arguments
#keyword arguments example
def college(name,marks):
    print('name=',name)
    print('marks=',marks)
#call student marks and pass arguments
college(name='sita',marks=75)
college(name='ravi',marks='60')
"""output:
name= sita
marks= 75
name= ravi
marks= 60
Note:
1: college('ravi', '60')# Valid
2: college(marks='80',name='rama')#Valid
3: college(marks='80', 'rama') #Error Positional arguments follows keyword
4: college(80,'rama') # Valid
5: college(n='sita',m=75)# Error


>>> """
We can pass arguments values by keyword i.e by parameter name
Here we are mentioning the keyword ‘name’ and another keyword ‘marks’. At the time of calling the function, we have to pass two values and we can mention which value is for what.
These keywords are nothing but parameter names which receive these values.
We can change the order of the arguments:
Ex: college(marks='80',name='rama')

3. Default Arguments:

#default arguments
def ex(a,pi=3.14159):
    print(a,pi)
ex(5)
ex(6,3.15)

"""output:
5 3.14159
6 3.15
>>> """
Sometimes we can provide default values for our positional arguments. If we are not passing any argument (actual parameter) from the function call then only default value will be considered.

5.     Variable length arguments

Previous: Passing parameters
Next: Introduction to *args and **kwargs in Python

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...