We have now reached yet another interesting part of the Python tutorial on building your own functions and default parameters.
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part 2 – Modules and Functions, Strings
- Starting up with Python – Part 3 – Sequences and List, Slicing and Editing
- Starting up with Python – Part 4 – More list functions and Slicing lists
- Starting up with Python – Part 5 – Methods
- Starting up with Python – Part 6 – Sort and Tuples, Strings and stuff, methods and Dictionary
- Starting up with Python – Part 7 – If statement, Else and elif statements
- Starting up with Python – Part 8 – Nesting and Comparison operators
- Starting up with Python – Part 9 – And and Or operators
- Starting up with Python – Part 10 – While, For, Infinite and Break Loops
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