Powered By Blogger

Mar 22, 2013


Functions in Python



Functions of Python performs specific task. By using functions we can reduce the duplication of code and can also increase the clarity of the code.  Functions can be assigned into variables, stored in collections or can pass as arguments.

Built-in functions and user defined functions are the two basic types.  Some of the examples of built-in functions are dir(), len() and abs().  The user defined functions are functions created with the ‘def ’  keyword.

The ‘def ’ keyword is followed by the function name with round brackets and a colon.  You can include the indented statements inside the body of the function.

def function_one():
    return ("hello")

When we call the function as function_one()the statements inside the function’s body are executed and gives the output as ‘hello’.

Functions can be defined inside a class those functions are known as ‘methods’.  A function can be defined inside the module (the file which we put the Python code) also the function can be defined inside another function and it’s called an “inner function”.

Methods:
class First_Class:
        @staticmethod
        def f():
        print “f() is a method”

Functions inside the Module:
def f():
        print “f() is a function”

Inner Functions:
def g():
        def f():
        print “f() is an inner function”
        f()


           

No comments:

Post a Comment