Posts

Showing posts with the label function

Python Anonymous/Lambda Function

Image
What are lambda functions in Python? In Python, anonymous function is a  function  that is defined without a name. While normal functions are defined using the  def  keyword, in Python anonymous functions are defined using the  lambda  keyword. Hence, anonymous functions are also called lambda functions. How to use lambda Functions in Python? A lambda function in python has the following syntax. Syntax of Lambda Function in python lambda arguments: expression Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required. Example of Lambda Function in python Here is an example of lambda function that doubles the input value. In the above program,  lambda x: x * 2  is the lambda function. Here  x  is the argument and  x * 2  is the expression that gets evaluated and return...

Python Recursion

Image
What is recursion in Python? Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. Python Recursive Function We know that in Python, a  function  can call other functions. It is even possible for the function to call itself. These type of construct are termed as recursive functions. Following is an example of recursive function to find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Example of recursive function In the above example,  calc_factorial()  is a recursive functions as it calls itself. When we call this function with a positive integer, it will recursively call itself by decreasing the number. Each function call multiples the number with the facto...