Python Functions and Lambda Functions Day - 12

Functions:

  • it's a block of code which is executed only if it is called, it can have any number of parameters to pass the data.

  • use def keyword to define a function and return inside the function to return a value.

  • Any data type can be sent as an argument to the function.

  • Default Arguments: Allows to define a function with default value assigned to one or more arguments. It uses default value if no value is passed, else the value gets overridden if any value is passed.

  • Arbitrary Arguments: If the number of arguments are not known, just place * before the parameter in function definition. (*args)

    • These arguments can be Positional or Keyword Arguments.

    • For Positional Arguments, an argument is prefixed with single asterisk (*) and it can store any number of values as shown in the example below.

    • For Keyword Arguments, an argument is prefixed with double asterisk(**) and that is stored as Dictionary(Key Value Pair)

  • Keyword Arguments: Allows to pass function arguments in the form of keywords, which are also known as 'Named Arguments'. Arguments with key = value can be sent. Arbitrary Keyword Arguments (**args)

    NOTE : Always the Positional Arguments(from above example, person('Ram','Hyderabad')) must be before the Keyword Arguments(from above example, person(name = 'Sita', location = 'Canada')).

  • Positional-Only Arguments: Use , / after the arguments.

  • Keyword-Only Arguments: Use *, before the arguments.

  • Default Parameter Value: If a function is called without argument, then it uses default value.

    *Lambda Function: It is an anonymous function.

  • It can have any number of arguments, but can have only one expression.

    | lambda function | function | | --- | --- | | Supports single-line statements that return some value. | Supports any number of lines inside a function block | | Good for performing short operations/data manipulations. | Good for any cases that require multiple lines of code. | | Using the lambda function can sometime reduce the readability of code. | We can use comments and function descriptions for easy readability. |