Sunday, April 1, 2012

Using Dictionary in Functions

Hello everyone, in this post I am going to discuss how to use dictionary in a function.

From the last post, we came to know how to create a function, and define a Tuple in a function that would take multiple values.

Now lets see how to use a dictionary.

Open up the Python Shell

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks

   
>>> sample('Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon')
Whiskey
('Good', 'Lovely', 'Kind', 'Poizon')
>>>

Well this was what we learnt from the last post, now lets see how to use a dictionary type in the function.

Whenever we use a dictionary type we need to indicate by double * (**) symbol before the variable.

Example:

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks


   
>>> sample('Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon', maths=76, science=78, computer=80)
Whiskey
('Good', 'Lovely', 'Kind', 'Poizon')
{'maths': 76, 'science': 78, 'computer': 80}
>>>

Well Note here, something, Python will automatically understand that a certain argument getting passed is a Dictionary value when it encounters the "=" symbol.

Also Note Something, we cannot change the order of values that we pass to a function.

Ex:

>>> def sample(name, *characteristics, **marks):
           print name
           print characteristics
           print marks

   
>>> sample(maths=76, science=78, computer=80, 'Whiskey', 'Good', 'Lovely', 'Kind', 'Poizon' )
SyntaxError: non-keyword arg after keyword arg
>>>

So we see here it gave an error, so we have to be careful about the order in which the values are passed.

So, This is all about the basics of playing with user defined functions, Practice it well, as while programming
every now and then its used to achieve certain outputs.

Thank You, and Don't Forget to check My next Post.

0 comments:

Post a Comment