Positional and Keyword Argument in python.

Positional Argument

If there are more then one parameters are present in a function, how does python idenify which argument in the statement has to assign which parameter. The parameter are assign accordings to their position i.e. first argument in the first column.

Example 1:

def display(name,mobile_no): print("Name:",name) print("Mobile_number:",mobile_no) display("Harsh",123456)

Output:

Name: Harsh Mobile_number: 123456

Example 2:

def display(name): print("Name:",name) display("Harsh",123456)

Error:

Traceback (most recent call last): File "<string>", line 7,in<module> TypeError:display()takes 1 positional argument but 2were given

Keyword Argument

An alternative to positional argument is keyword argument. If the program knows the parameter name use within the function then they can use the parameter name by calling the function. This is done by:

Parameter_name=value

Example:

def display(name,mobile_no): print("Name:",name, "Mobile_number:",mobile_no) display(mobile_no=123456, name="Harsh")

Output:

Name: Harsh Mobile_number: 123456

Precautions of using Keyword argument:

1. A positional argument can not follows keyword argument.

Example 1:

def display(name,mobile_no): print("Name:",name, "Mobile_number:",mobile_no) display("Harsh",mobile_no=123456)

Output

Name: Harsh Mobile_number: 123456

Example 2:

def display(name,mobile_no): print("Name:",name, "Mobile_number:",mobile_no) display(mobile_no=123456,"Harsh")

Error:

File "<string>", line 7 SyntaxError: positional argument follows keyword argument

2. We can not duplicate an argument by specifying it by as both positional and keyword argument.

Example:

ef display(name,mobile_no): print("Name:",name, "Mobile_number:",mobile_no) display("Harsh"name="Harshwardhan")

Error:

File "<string>", line 6display ("Harsh"name="Harshwardhan")^ SyntaxError: invalid syntax

Parameter with Default value:

Parameter within function definition can have default values, we can provide default value to a parameter using assignment operator.

def circle_area(radius,pi=3.14): print("Area of circle:", radius*radius*pi) circle_area(4)

Output:

Area of circle: 50.24

When we pass the actual value even a default value is define in function, it will overwrite the default value.

def circle_area(radius,pi=3.14): print("Area of circle:", radius*radius*pi) circle_area(4,4)

Output:

Area of circle: 64

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.