Wednesday, March 28, 2012

How to add Default Parameters

Hello Everyone, In This post we will see how to add default parameters to functions that we define in a Python Script. You might have noticed I have started using the word script, instead of Python Program, Yes, technically Python Programs are known as Scripts, which are heavily used in Desktop Applications and Web Development Applications. As a matter of fact, Web Browser Opera is made in Python, so as the application Google Earth, there are many more examples, we are yet very far from those topics.

Lets get back to the topic.

Suppose we write a script and define some functions, and the script is used by system administrators or network administrators for some automated tasks, like bulk copying or deleting or sharing, etc, etc. So what if the user dsnt inputs anything for the parameters of the functions defined? The script will choke and We don't want that isn't it?

So here is what we do, we add some default values to the functions:

>>> def name(first,last):
              print '%s  %s' % (first,last)

>>> f = 'Python'
>>> l = 'Script'
>>> name(f,l)
Python Script
>>> name()

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
TypeError: name() takes exactly 2 arguments (0 given)

So we see here, if there is no arguments passed for the function, it choked

What we can do is, just modify and add a default value to the arguments of the functions:

>>> def name (f_name='Fatal', l_name='Error'):
              print "%s %s" % (f_name, l_name)

>>> name()
Fatal Error
>>>  name('Hello', 'World')
Hello World
>>> name(f,l)
Python Script

So we see here that, when no arguments is passed, it returns or displays the default value.

And when argument is passed, it displays the arguments that has been passed.

So I hope This Has been Informative To you, Practice it, And Don't forget to check the next Post.

Thank You.


Post a Comment