top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Writer's picture074bex435.ranjan

Python Concepts for Data Science: *args and **kwargs

Function is an inevitable part in programming which reduces the redundant task to be performed. If the number of variables to be passed as function argument, then we can do it in normal way as:

def func(a,b,c):
    print("The statement is "+a+ " " + b + " " + c)
func("Data","Insight","Online")

Output
The statement is Data Insight Online

But if we don't know the number of function arguments, then we use special symbols as:

  • *args(Non-keyword argument)

  • **kwargs(Keyword argument)


*args

Keyword is not required while passing arguments. The arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the parameter excluding asterisk *.

def withArgs(*args):
    print(args)
withArgs(3,4,5)


Output
(3, 4, 5)

Here *args is used but we can use anything instead of args but * should be present before it. Example, *num, *dummy, etc.


**kwargs

If we want to pass keyword along with arguments, the **kwargs is used. The arguments are passed as dictionary.

def withKwargs(**foo):   
    print(foo)
    for key, value in foo.items():
        print("Key={},Value={}".format(key,value))
withKwargs(name="abc",surname="def",gender="M")

Output
{'name': 'abc', 'surname': 'def', 'gender': 'M'} Key=name,Value=abc Key=surname,Value=def Key=gender,Value=M 

As similar to *args, we can use any dummy value after double asterisk(**). Due to the dictionay nature, we accessed the values as key, value pair.


0 comments

Recent Posts

See All

Comentários


bottom of page