Skip to content

Functions

A function is a rules that takes a set of inputs a returns a corresponding output.

Definition

def function_name(param):
    """
    Docstring where the documentation of the function is present
    """
    print("Output: "+ str(param))
    return param

Assignment

function_copy = function_name
result = function_copy(10)
Output: 10

Lambda Functions

You can assign an annonymous (i.e. lambda) function to a variable

lambda_output = lambda x: x * 2
output = lambda_output(2)
print(output)
4

You can also create an lambda function that is passed as a parameter to another function

def lambda_function(f):
    return f(1)

lambda_output = lambda_function(lambda x: x*2)
print(lambda_output)
2

Default Parameters

def sample_function(first="Hello", second="World"):
    return first + " " + second

print(sample_function("Hi"))
print(sample_function("Hi", "Amgad"))
print(sample_function(first="Hi", second="Amgad"))
Hi World
Hi Amgad
Hi Amgad