A function is a block of reusable code which can be defined and used as many as you want. A function take some parameters(optional) and return some value or perform any action as per parameters. There are 2 types of function in python.
- Built in Functions
- Custom Defined Functions
Built in functions are function which are provided by python like print(), len() etc.
Custom functions are defined by user as per working requirements
How to Create
A function can be created by def keyword and function name, function inner block also written with ident block if ident is not used interpreter will through an error. Example
def new_function(): print("Hello Word")
How to call
A function can be called by its name and round brackets like above function we can call like.
This function will print Hello Word
Parameter of function
A parameter is a value or a set of values which can be passed to function and perform different action inside the function block we can pass parameters to function with different styles like.
def my_function(fname): print(fname + " Refsnes") my_function("Emil") #Will Print Emil Refsnes
You can pass as many parameters as you want there are more styles available for passing parameters here is a list and details.
- def my_function(fname, lname): Will accept 2 parameters
- def my_function(*kids): Will used if parameter quantity is unknown parameters can be accessed by its index like kids, kids
- def my_function(param_1, param_2, param_3): Param also can be passed by param name when a function is called like my_function(param_1 = ‘a’ , param_2 = ‘b’, param_3 = ‘c’) in this method order does not matter
- def my_function(fname = ‘john’ , lname): Will accept fname as john if no value provided by user
After performing some action a function can also returned a value of any type
def my_function(x): return 5 * x print(my_function(3)) #will return the answer of 5*3 and print function will print it 15
If you want to leave empty a function block and do not want to perform any action on it you can use simply pass keyword inside the function block