Functions, like in any programming languages, are the smallest reusable building blocks of an application. In Python, we can declare and define the functions in the following ways.
To create a function we use "def" keyword in Python. To call a function simply write the function name followed by opening and closing circular braces.
def foo(): print("This is foo") foo()
We can pass any number of arguments to the function.
def bar(x, y) print("Sum is ", x + y) bar(3, 5);
We can pass default value for the argument of a function. So, if the value is not provided while calling the function, the parameter is initialized with the default value.
def drawLine(length = 10): str = "" for i in range(0, length): str += "_" print(str)
Calling with no parameter, so value of parameter length will be initialized 10 by default.
Here value of parameter length will be initialized as 40.
We can also use argument name to pass value. This is useful when we dont want to pass parameters in sequence or skipping any default parameter.
Lambda expressions are used create anonymous functions. This is created with "lambda" keyword.
def greeter(val): return lambda x: val + x greet = greeter("Hello ") print(greet("Alice!")) print(greet("Bob!"))
By expression "lambda x: val + x", we mean that it is a lambda expression (or anonymous function) takes the input "x" and appends it to some string "val".
Recursive function are the function that call themselves in the function body. The necessary requirement of every recursive function is that it must converge to a terminating condition. The following function evaluates the factorial of an input integer.
def factorial(x): if x == 1: return 1 else: return (x * factorial(x-1)) x = 4 print("The factorial of", x, "is", factorial(x))
Access Jupyter notebook for this chapter here:
Python Notebook - Functions