What is a function and how to define a function

Creating Your Own Functions

function provides us a way to group statement. After we create a function we can call the function by using the function name.

To create a function we use def keyword.


def hello(name): 
    return 'Hello, ' + name + '!' 
print hello('world') 

The code above generates the following result.

A function that returns a list of the numbers of the Fibonacci series


def fib2(n): # return Fibonacci series up to n
     """Return a list containing the Fibonacci series up to n."""
     result = []#   w  w w . j  a v a 2s .  co  m
     a, b = 0, 1
     while b < n:
         result.append(b)    # see below
         a, b = b, a+b
     return result
 
f100 = fib2(100)    # call it
print f100          # write the result

The code above generates the following result.

Forward References

The following code shows that we can forward reference a function.


# from  w  ww  .  jav a 2 s  .c o m
def bar():
    print 'in bar()'

def foo():
   print 'in foo()'
   bar()

foo()

The code above generates the following result.

In fact, we can even declare foo() before bar():


def foo():#  w w  w  . j  a  v  a2s. c  om
    print 'in foo()'
    bar()

def bar():
    print 'in bar()'

foo()

The code above generates the following result.

An inner function


def foo():# from ww  w  . j  a  v a 2 s.c  o m
    def bar():
        print 'bar() called'

    print 'foo() called'
    bar()

foo()

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules