Saturday, May 13, 2023

#PYTHON(DAY17)Args and Kwargs

 

#PYTHON(DAY17)

args and kwargs

We use args and kwargs as an argument when we are unsure about the number of arguments to pass in the functions.

Special Symbols Used for passing arguments in Python:

  • *args (positional Arguments)
  • **kwargs (Keyword Arguments)

What is Python *args?

The special syntax *args in function definitions in Python is used to pass a variable number of arguments to a function. It is used to pass a positional argument, variable-length argument list.

  • The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
  • What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
  • For example, we want to make a multiply function that takes any number of arguments and is able to multiply them all together. It can be done using *args.
  • Using the *, the variable that we associate with the * becomes iterable meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.

Example:

def myFun(*argv):
for arg in argv:
print(arg)


myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

And the output is:

Hello
Welcome
to
GeeksforGeeks

What is Python **kwargs?

The special syntax **kwargs in function definitions in Python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

  • A keyword argument is where you provide a name to the variable as you pass it into the function.
  • One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))


# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

And the output is:

first == Geeks
mid == for
last == Geeks

return

  • if our intention is to capture and reuse the value given by our user defined function, then we need to use ‘return’ statement
  • ‘return’ will return the value/s passed to it and comes outside the function block with the value given to it
# using return
def foo(x,y,z):
return (x+y)*z

a = foo(2,3,4)
print(a)

And the output is:

20

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...