A convenient way to divide the code into useful blocks is by using what we call as a function. A function can be understood as block of instructions that performs a single and related action. The use of functions in a code makes it more readable and saves the programmer’s time. Functions can be classified as built-in functions and user-defined functions. Built-in functions as the name suggests are already a part of the Python library. These are predefined in the Python programming interface. On the other hand, user-defined functions are the functions that are invoked or called by the user to be used in a code. These types of functions are not pre-existing and are defined as per the user’s imagination.
In Python, a function is defined using a special word (we call key word: def), followed by the name of the function and the place holders (arguments) for the values when we call this function.
Python has many built-in functions such as: print( ) : Prints an object specified in the code as an output. int( ) : Converts a string or a number datatype to an integer datatype. len( ) : Returns the length of an object.
Syntax: def functionname( parameters ):
Example: def printas( str ):“This prints a passed string into this function” print(str) return # Now you can call printas function printas(“My Name is XYZ”) printas(“I love Python programming”)
Output This code will generate the following output: My Name is XYZ I love Python programming
Note that the function “print(str)” is a built-in function whereas “printas( )” is a user-defined function.