Get more out of Python – Functions


When coding it is often useful to be able to create a function that allow reuse of code throughout your program.  The good news is that Python allows you to create your own functions.  Functions are very easy to create and use.  Lets look as a simple example:

def  joinLists(lstFirst,lstEnd):
return lstFirst + lstEnd

A few things to note when declaring a function:

  1. The word def is used to define a function
  2. The function name needs the () after it regardless of arguments being required
  3. A full colon : is required after the function name
  4. The contents of the function are indented
  5. The return statement returns the result (you don’t need this if you only want to say print a few lines to the screen)
  6. The function must be declared before it is called
Let’s look at how we can use this function is some code:
#A short script to test a function
#Define the function before calling it

def  joinLists(lstFirst,lstEnd):
return lstFirst + lstEnd

def printAnswer(value):
print “The new list is ” +  str(value)

l1=[1,2,3,4]
l2=[5,6,7,8]
#an example of a function call as an argument
printAnswer(joinLists(l1,l2))

#end of our program

Cheers

Stephen B

Got something to say?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s