Tuesday, March 27, 2012

How To Build Own Functions

Hello everyone, in this post we will see how to make our own functions, till now we have used functions that were built-in to Python. But many a times while writing a script we need to repeat certain things over and over again, wish there was something that would make life easy...Yes this is where building own functions comes handy.

How do you create own functions?

Its simple, we just need the key word def and the syntax is:

def function_name(arguments):

Note: User-Defined Functions are valid only for one script. Function created for one script is not valid for other script.

Now lets check out some created functions

>>> def var_a(x):
            return "Whats Your Social Security Number, "+x+"?"

>>> print var_a("Python")
Whats Your Social Security Number Python?

So whenever we call the defined function "var_a" with an argument, it returns the result after executing the codes under functions.

Okay, so by now I am guessing why no one asked how to clear the shell while working with the Python Shell. When I was learning python, I wanted to know how to clear the window of the Python Shell. In Windows Command Shell, when we type "cls" it clears the Window, In Linux Shell when we type "clear" it clears the window, but unfortunately, Python doesn't have such command, but programmers are genius, there is a trick which can clear up the window for you, and guess what its by the user-defined function, lets check it out how.

>>> def clearpy():
             return "\n"*50

>>> print clearpy()

So when we call the defined function clearpy(), as expected it will print 50 new blank lines, thus making the Shell looking decent and clean.

Okay, So I Hope This was Informative For you, practice this and make sure you will not be surprised when I use the def functions in future posts.

Thank You!


Post a Comment