Functions#

The basics about functions#

Defining and calling a function

Example#
 1#!/usr/bin/env python3
 2
 3def my_function():
 4    print("Hello from a function")
 5
 6
 7def main():
 8    my_function()
 9
10
11if __name__ == "__main__":
12    main()

Calling a function multiple time and scope of the variables

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(fname):
 4    print(fname + " Refsnes")
 5
 6
 7def main():
 8    my_function("Emil")
 9    my_function("Tobias")
10    my_function("Linus")
11
12
13if __name__ == "__main__":
14    main()

Using return

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(x):
 4    return 5 * x
 5
 6
 7def main():
 8    print(my_function(3))
 9    print(my_function(5))
10    print(my_function(9))
11
12
13if __name__ == "__main__":
14    main()

Default values

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(country = "Norway"):
 4    print("I am from " + country)
 5
 6
 7def main():
 8    my_function("Sweden")
 9    my_function("India")
10    my_function()
11    my_function("Brazil")
12
13
14if __name__ == "__main__":
15    main()

Passing multiple arguments#

Index based with *args

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(*kids):
 4    print("The youngest child is " + kids[2])
 5
 6
 7def main():
 8    my_function("Emil", "Tobias", "Linus")
 9
10
11if __name__ == "__main__":
12    main()

Keyword based with **kwargs

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(**kid):
 4    print("His last name is " + kid["lname"])
 5
 6
 7def main():
 8    my_function(fname = "Tobias", lname = "Refsnes")
 9
10
11if __name__ == "__main__":
12    main()

Using yield instead of return#

Example#
 1#!/usr/bin/env python3
 2
 3def multi_yield():
 4    yield_str = "This will print the first string"
 5    yield yield_str
 6    yield_str = "This will print the second string"
 7    yield yield_str
 8
 9
10def main():
11    multi_obj = multi_yield()
12    print(next(multi_obj))
13    print(next(multi_obj))
14    print(next(multi_obj))
15
16
17if __name__ == "__main__":
18    main()

Map, Filter and Reduce#

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(n):
 4    return len(n)
 5
 6
 7def main():
 8    x = map(my_function, ('apple', 'banana', 'cherry'))
 9    prin(x)
10    print(list(x))
11
12
13if __name__ == "__main__":
14    main()

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(x):
 4    if x < 18:
 5        return False
 6    else:
 7        return True
 8
 9
10def main():
11    ages = [5, 12, 17, 18, 24, 32]
12    adults = filter(my_function, ages)
13    print(list(adults))
14
15
16if __name__ == "__main__":
17    main()

The functools.reduce()

Example#
 1#!/usr/bin/env python3
 2
 3from functools import reduce
 4
 5def my_function(a, b):
 6    result = a + b
 7    print(f"{a} + {b} = {result}")
 8    return result
 9
10
11def main():
12    numbers = [0, 1, 2, 3, 4]
13    reduce(my_function, numbers)
14
15
16if __name__ == "__main__":
17    main()

Introduction to Lambda#

A lambda function is an anonymous function

Syntax#
1lambda arguments : expression
Example#
1#!/usr/bin/env python3
2
3def main():
4    x = lambda a : a + 2
5    print(x(2))
6
7
8if __name__ == "__main__":
9    main()
Output#
14
Example#
1#!/usr/bin/env python3
2
3def main():
4    x = lambda a, b : a + b
5    print(x(2, 3))
6
7
8if __name__ == "__main__":
9    main()
Output#
15

Using Lambda functions#

Example#
 1#!/usr/bin/env python3
 2
 3def myDouble(x):
 4    return lambda a : a * x
 5
 6
 7def main():
 8    double = myDouble(2)
 9    print(double(3))
10    print(double(4))
11
12
13if __name__ == "__main__":
14    main()
Output#
16
28