Starting up with Python – Part 11

We have now reached yet another interesting part of the Python tutorial on building your own functions and default parameters.

25. Building functions

We have been using several built-in functions in Python. This time we are going to build our own functions. We will start by defining the function – see line1. After having defined the function, we will need to tell the function what to do. Here is an example where a function is created and instructed what to do.

>> def hackers(x):
... return 'whats up mauritius' + x

Now, the function is used just by inserting the following line. As you can see it returns friends by using the function hackers.

>> print hackers(' friends')
whats up mauritius friends

Another example where a function can be created is by adding a specific number.

>> def addition(z):
... return z+10
... 
>>> print addition(10)
20

26. Default Parameters

Default parameter in the functions is used instead of having a default value. Here is an example of a simple basic function which takes two parameters.

>> def continent(east,west):
... print '%s %s' % (east, west)
... 
>>> continent('australia', 'africa')
australia africa

Now, the function has rewritten a function that already has default values in it. Here is an example. We also noticed that the continent function gave the value Australia and Africa directly.

>> def continent(east='australia', west='africa'):
... print '%s %s' % (east, west)
... 
>>> continent()
australia africa

But what if we want to overwrite Africa and use Madagascar instead? Here is the catch. Whenever a specific value is given, it will overwrite the default value otherwise use the default values

>> continent('australia','madagascar')
australia madagascar
>>> continent()
australia africa 

You can also overwrite default values as such:

>> continent(west='usa')
australia usa
Nitin J Mutkawoa https://tunnelix.com

Blogger at tunnelix.com | Founding member of cyberstorm.mu | An Aficionado Journey in Opensource & Linux – And now It's a NASDAQ touch!

You May Also Like

More From Author