All about Functions – Python 3

Now let us get into functions. Functions can be pre-defined and user defined. As part of user defined functions we need to understand different ways to define and pass arguments and also lambda functions.

  • Pre-defined Functions
  • String Manipulation Functions
  • Defining Functions and Returning Values
  • All about Function Arguments
  • Defining Lambda Functions
  • Usage of Lambda Functions

Pre-defined Functions

As part of this topic let us check some of the important pre-defined functions.

  • help
  • type
  • Type Casting functions
  • Reading data from files into collection

String Manipulating functions

String Manipulation functions are the most extensively used functions in any programming language.

  • len
  • count
  • index and find
  • Case Conversion Functions
    • lower
    • upper
    • swapcase
  • Trimming functions
    • strip
    • rstrip
    • lstrip
  • Padding Functions
    • rjust
    • ljust
  • join (concatenate)
  • split and splitlines
  • Validate Functions
    • isspace
    • islower
    • isupper
    • isdigit
    • isalpha
    • isalnum
  • and more
  • Understanding string manipulating functions is very important for processing the data

Defining Functions

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it.

Here are simple rules to define a function in Python –

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
  • The first statement of a function can be an optional statement – the documentation string of the function or docstring.
  • All parameters (arguments) in the Python language are passed by reference.

 Return Statement

  • The return statement is used to return from a function i.e. break out of the function.
  • Every function implicitly contains a return None statement.
  • Python supports multiple returns.

Function Arguments

Let us understand details about Function Arguments.

  • Default arguments
    • For some functions, you may want to make some parameters as optional and use default values if the user does not want to provide values for such parameters. This is done with the help of default argument values.
    • Note that the default argument value should be immutable. You cannot use mutable objects such as lists for default argument values.
  • Keyword arguments
    • If you have some functions with many parameters and you want to specify only some parameters, then you can give values for such parameters by naming them this is called keyword arguments.
    • This has two advantages – One, using the function is easier since we do not need to worry about the order of the arguments.Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.
  • Required arguments
    • Required arguments are the arguments passed to a function in correct positional order. Here the number of arguments in the function call should match exactly with the function definition.
  • Variable-length arguments
    • You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
    • An asterisk (*) is placed before the variable name that will hold the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.
  • Keyword only-parameters
    • If we want to specify certain keyword parameters to be available as keyword-only and not as positional arguments, they can be declared after a starred parameter

Lambda Functions

Let us explore more about Lambda Functions in Python.

  • Lambda keyword can be used to create small anonymous functions.These functions are called anonymous because they are not declared in the standard manner by using the def keyword.
  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression.
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
  • Lambda Operator or Lambda function
    • The lambda operator is a way to create small anonymous functions, i.e. functions without a name.
    • These functions are throw-away functions, i.e. they are just needed where they have been created.
    • lambda is an expression, not a statement.
    • lambda’s body is a single expression, not a block of statements.
    • It is primarily used to pass small expressions as functions
  • Sum of numbers

Usage of Lambda Functions

Let us see examples of Lambda Functions to understand the usage of it.

  • Some of the APIs which uses lambda functions that can be applied on collections
    • map
    • reduce
    • filter

  • map()
    • The t = map(func, s) – function applies the function func to each of the elements in “s” and returns a new list, t.

  • filter()
    • The filter(func,s) function filters the elements of s using a filter function, func(), that returns true or false. A new sequence is returned consisting of all elements, x of s, for which func(x) is true.

  • reduce()
    •  Reduce is a really useful function for performing some computation on a list and returning the result.
    • From python 3 it is part of functools