Functions are used to make certain portions of codes reusable and are a great tool to bring efficiency in the codes. In Python, we define a function using keyword “def” followed by the name of the function, the parameters and the indented block which will execute the function to produce a certain output. Let’s look at few examples.
The first function is called “hello” and it takes no parameter and will print “This is my first python function and I’m so excited”, whenever this function is called [ hello ()].
Defining a simple function called “Hello” to print the below message
Functions may be given parameters and default values, in case the user is not providing or overwriting the default values, the function will use these values to process the codes.
Defining a function called “sqr” to square a number. The default value given is 2
Defining a function to add three numbers with default values. Can you figure out what the below Python function is doing? What are the default values?
Anonymous or Lambda Functions are short functions which are generally written in a single line. For example, the below set of codes show you how we can use Lambda function to cube a number, instead of defining a function.
Moreover, the Lambda functions can be assigned to a variable as shown in the above code, where we are assigning it to the ‘cube’ variable.
Python also has a host of in built functions – Inbuilt Functions
Thanks for reading!
You must be logged in to post a comment.