Keyword arguments function in python

Previous
Next

Keyword arguments:

  • Generally parameter values will store into arguments from left to right.
  • In the below code, when we pass name and age, the values stores according into arguments.
def keyword(name, age):
    print("Name is :", name)
    print("Age is :", age)
    return

keyword("Annie", 21)

Look into this following code, when we change the order of parameter values:

def keyword(name, age):
    print("Name is :", name)
    print("Age is :", age)
    return


keyword(21,"Annie")
  • Keyword arguments are useful to pass values using argument names as parameters
  • We can pass values in any order when we use arguments as keys.
def keyword(name, age):
    print("Name is :", name)
    print("Age is :", age)
    return

keyword(age=21, name="Annie")

Keyword arguments are very useful when we are working with default arguments function.

def default(a=10, b=20, c=30, d=40):
    print("a val :",a)
    print("b val :",b)
    print("c val :",c)
    print("d val :",d)
    return

default(10,20,50,40)

In the above application, we can easily modify the “c” value using keyword arguments.

def default(a=10, b=20, c=30, d=40):
    print("a val :",a)
    print("b val :",b)
    print("c val :",c)
    print("d val :",d)
    return

default(c=50)

Code to understand keyword arguments advantage:

  • Consider circle function in programming.
  • When we call simply circle(), it draws a circle with all default values.
  • We can specify the changes in circle using keyword arguments easily.
def circle(color="black", x=100, y=100 , rad=50):
    print("circle prints @ (",x,",",y,") with radius :",rad,"in",color)
    return

circle()
circle(rad=75)
circle(color="red")
Previous
Next

Add Comment

Courses Enquiry Form