In this tutorial you will learn about the Python Functions and its application with practical example.
Python Functions
In Python, functions are one of the important part of any python program. Python function gives you way to wrap up the set of statements that means to perform any specific task and give it a name, so that it can be invoked later from any where in the program.
Functions makes it easy to divide the complete program into sub-units that perform a specific task for that program, this way it enhance the modular approach and increase the code re-usability of the program.
We pass information in function call as its parameter and the function can either returns some value to the point it where it called from or returns nothing.
Advantages of function
- It enhance the modularity of the program.
- It enhance the re usability.
- It makes development easy as development can be shared in team.
- It reduces the coupling.
- It reduces duplication.
Type Of Function
- Built in function
- User defined functions
Built In Function In Python
Built in functions are the functions available in Python Programming Language to perform some common and standard tasks that includes the functions for file access, mathematical computations, graphics, memory management etc.
User defined functions In Python
User defined function are custom function defined by user it self to perform as custom task that is not available as built in, in this way user can define and write subprograms as functions to perform a task relevant to their programs.
Defining Function In Python
Syntax:-
1 2 3 |
def <function_name>(<parameter_list>): """docstring""" statement(s) |
Example:-
1 2 3 4 5 |
def add(x, y): """Return x plus y""" return x + y print add(4,5) |
Output:-
1 |
9 |
Function with Optional Parameters
Example:-
1 2 3 4 5 6 |
def add(x, y=5): """Return x plus y, optional""" return x + y print add(3) print add(4,2) |
Output:-
1 2 |
8 6 |