Friday, March 30, 2012

Multiple Parameters

Hello Everyone, in this post, we will check how to add multiple parameters to a functions, we need to this trick many a time while programming a script..

Okay lets get started.

First lets make a function

>>> def python(name):
           print name

>>> python('PythonGame')
>>> python('Python', 'Game')

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    python('Python', 'Game')
TypeError: python() takes exactly 1 argument (2 given)

Well what happened is, we made a function take takes only one argument, and if we pass, more than one argument, it gives an error, as it cannot handle more than one.

Now, lets see how can we make it work, i.e to accept multiple arguments..

>>> def python(*name):
           print name

>>> python('Python', 'Game', 'Snake')
('Python', 'Game', 'Snake')

It it took three arguments and worked absolutely fine, and returned a Tuple. So this is the trick, we need to add a * symbol while defining the argument of the function.

Now, to clear the confusion, if you have any, lets check one more example

Lets say, we have been given a task, where the output should display software/application name along with platform supported.

>>> def soft(name, *support):
          print name
          print support

>>> soft('Python', 'Windows, Linux, MAC')
('Windows, Linux, MAC',)
>>> soft('Python', 'Windows', 'Linux', 'MAC')
('Windows', 'Linux', 'MAC')

Well I guess this should be clear with you, and these posts are very important, please try to understand them well.

Thank You and Don't forget to check my next post.


Post a Comment