**A training to acquire strong basis in Python to use it efficiently**
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code
reusing.
%% Cell type:markdown id: tags:
## Simple function definitions and calls
Function blocks begin with the keyword `def` followed by the function name and parentheses (`()`).
- The code block within every function starts with a colon (:) and is indented.
- Any input parameters or arguments should be placed within these parentheses.
%% Cell type:code id: tags:
``` python
defprint_hello():
"hello printer"
print('hello')
defmyprint(s):
"my hello printer"
print('I print',s)
# function calls
print_hello()
print_hello()
myprint('First call of myprint')
myprint('Second call of myprint')
```
%%%% Output: stream
hello
hello
I print First call of myprint
I print Second call of myprint
%% Cell type:markdown id: tags:
## Simple function definitions and calls
- The first statement of a function can be the documentation string of the function, also called "docstring".
- The statement `return [expression]` exits a function, optionally passing back an expression to the caller. No return statement or a return statement with no arguments is the same as `return None`.
(Note: Wikipedia about duck typing: https://fr.wikipedia.org/wiki/Duck_typing)
%% Cell type:code id: tags:
``` python
importunittest
defadd(arg0,arg1):
"""Print and return the sum of the two arguments (duck typing)."""
## All Python functions return exactly one object but... `None` and `tuple`
%% Cell type:code id: tags:
``` python
type(print())
```
%%%% Output: stream
%%%% Output: execute_result
NoneType
%% Cell type:code id: tags:
``` python
defreturn_a_tuple():
return1,'hello',3# a tuple, same as (1, 'hello', 3)
my_tuple=return_a_tuple()
print(my_tuple)
```
%%%% Output: stream
(1, 'hello', 3)
%% Cell type:code id: tags:
``` python
a,b,c=return_a_tuple()
print(b)
```
%%%% Output: stream
hello
%% Cell type:markdown id: tags:
## Function call: namespaces and objects "passed by references"
For each function call:
- a **new namespace** is created (as at the beginning of a module)
- the objects are **"passed by references"**: new names of the arguments are created in the function namespace and they point towards the objects given as arguments to the function (so it is possible to modify the mutable objects).
%% Cell type:markdown id: tags:
## Function call: objects "passed by references"
Exercice: use 2 schemes "namespaces-objects" to understand these 2 pieces of code.
%% Cell type:code id: tags:
``` python
number=2
mylist=[]
defmy_strange_append_square(l,n):
# new function namespace with names "l" and "n"
n=n**2
l.append(n)
my_strange_append_square(mylist,number)
print(mylist,number)
```
%%%% Output: stream
[4] 2
%% Cell type:code id: tags:
``` python
number=2
mylist=[]
mylist=[17]
defmy_strange_append_square(mylist,number):
# new function namespace with names "mylist" and "number"
number=number**2
mylist.append(number)
mylist.append(number)
print("das f",mylist)
my_strange_append_square(mylist,number)
my_strange_append_square(mylist[:],number)
print(mylist,number)
```
%%%% Output: stream
[4] 2
das f [17, 4]
[17] 2
%% Cell type:markdown id: tags:
## Global vs Local variables
Variables that are defined inside a function body have a local scope (i.e. are defined in the function namespace), and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the module by all functions.
%% Cell type:code id: tags:
``` python
# global variables
result=0
multiplicator=2
defmultiply(arg0):
# here we create a new name `result` in the function namespace
# `result` is a local variable
# we can use the global variable `multiplicator`
result=multiplicator*arg0
print('Inside the function local result:\t',result)