Introduction#
Functions are a convenient way to divide your code into useful blocks, allowing to order the code, make it more readable, reusable and save some time. Also, functions are a key way to define interfaces, so programmers can share their code.
Function#
In order to build a function we must start by the block keyword def follow by the name of the function, parenthesis and a column, in the next line the code block of the function to be executed. In the parentheses you can add the parameters you want to implement inside the function, you can add as much as you wish.
1
2
3
4
5
6
7
| def compteur_complet(start, stop, step):
i = start
while i < stop:
print(i)
i = i + step
compteur_complet(1, 7, 2)
|
Output:In order to present the results of the function code block you must use the keyword return follows by the variables to output.
1
2
3
4
5
6
7
8
| def volume_sphere(r):
cube = r**3
V = 4 / 3 * np.pi * cube(r)
return V
sphere = volume_sphere(3)
print(f"The sphere volume is {sphere} cubic meters")
|
Output:1
| The sphere volume is 36 cubic meters
|
global and local variables#
While working with functions you can be found yourself to two kind of variables, the local variables that are declared inside the function and does not interact outside the function and the global variables that are declared inside the function and override any existent outside the function domain.
1
2
3
4
5
6
7
8
| def test():
b = 5
print(a, b)
a = 2
b = 7
test()
print(a, b)
|
Output:To declare a global variable the procedure is as simple as to use the global keyword inside or outside the function.
1
2
3
4
5
6
7
8
9
| def test():
global b
b = 5
print(a, b)
a = 2
b = 7
test()
print(a, b)
|
Output:Sometimes, we do not know in advance the number of arguments that will be passed into a function. To handle this kind of situation, we can use arbitrary arguments and keyword arguments.
Arbitrary arguments allow us to pass a varying number of values during a function call. Meanwhile, keyword argument allow us to pas a varying dictionary during a function call.
We use an asterisk (*) before the parameter name to denote kind of argument and the double asterisk (**) before the parameter group to denote this kind of dictionary.
1
2
3
4
| def flexible_function(*args, **kwargs):
print("Positional args:", args)
print("Keyword args:", kwargs)
flexible_function(1, 2, name="Bob", job="Engineer")
|
Output:1
2
| Positional args: (1, 2)
Keyword args: {'name': 'Bob', 'job': 'Engineer'}
|
Lambda function#
Normally we define a function using the def keyword somewhere in the code and call it whenever we need to use it. Instead of defining the function somewhere and calling it, we can use lambda functions, which are inline functions defined at the place we need it.
They don’t need to have a name, so they also called anonymous functions. We define a lambda function using the keyword lambda as follows:
function = lambda inputs : output
1
2
3
4
5
| test = lambda x,y : x**2 + Y**2
a = test(2,7)
print(a)
|
Output:Comprehensions#
This is not a function by itself, but it can be used with lambda functions to create list, dictionary and set in a condensed manner. They all follow the same logic for deployment.
expresion for item in iterable [if condition]
The if-else condition are not mandatory, but optional as a filtering step. The main difference is in the enclosure for each one.
list comprehension#
[expresion for item iterable (if condition)]
1
2
3
4
5
| squares = [n * n for n in range(1, 6)]
even_squares = [n * n for n in range(1, 11) if n % 2 == 0]
print(even_squares)
print(squares)
|
Output:1
2
| [4, 16, 36, 64, 100]
[1, 4, 9, 16, 25]
|
if-else clause:
1
2
3
4
5
6
| sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) if word != "the" else 0 for word in words]
print(words)
print(word_lengths)
|
Output:1
2
| ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[0, 5, 5, 3, 5, 4, 4, 3]
|
set comprehension#
{expresion for item iterable (if condition)}
1
2
3
4
5
| squares = {n * n for n in range(1, 6)}
even_squares = {n * n for n in range(1, 11) if n % 2 == 0}
print(even_squares)
print(squares)
|
Output:1
2
| {4, 16, 36, 64, 100}
{1, 4, 9, 16, 25}
|
if-else clause:
1
2
3
4
5
6
| sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) if word != "the" else 0 for word in words]
print(words)
print(word_lengths)
|
Output:1
2
| ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[0, 5, 5, 3, 5, 4, 4, 3]
|
dictionary comprehension#
{item : expresion for item iterable (if condition)}
1
2
3
4
5
| squares = {n : n * n for n in range(1, 6)}
even_squares = {n : n * n for n in range(1, 11) if n % 2 == 0}
print(even_squares)
print(squares)
|
Output:1
2
| [4, 16, 36, 64, 100]
[1, 4, 9, 16, 25]
|
if-else clause:
1
2
3
4
5
6
| sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = {word : len(word) if word != "the" else 0 for word in words}
print(words)
print(word_lengths)
|
Output:1
2
3
| ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
{'the': 0, 'quick': 5, 'brown': 5, 'fox': 3, 'jumps': 5, 'over': 4, 'lazy': 4,
'dog': 3}
|