**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:
## 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=[]
defmy_strange_append_square(mylist,number):
# new function namespace with names "mylist" and "number"
number=number**2
mylist.append(number)
my_strange_append_square(mylist,number)
print(mylist,number)
```
%%%% Output: stream
[4] 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)
returnresult
multiply(10)
print('Outside the function global result:\t',result)
```
%%%% Output: stream
Inside the function local result: 20
Outside the function global result: 0
%% Cell type:markdown id: tags:
- Global variables can be used in a function.
- Global variables can not be modified in a function (except with the `global` keyword. Discourage!).
%% Cell type:markdown id: tags:
## Global vs Local variables: `global` keyword
There is a keyword `global` to define inside a function a global variable and to modify a global variable in the function. **It is often a bad idea to use it :-)**
%% Cell type:code id: tags:
``` python
deffunc():
globalme
# Defined locally but declared as global
me='global variable locally defined'
print(me)
func()
# Ask for a global variable
print(me)
```
%%%% Output: stream
global variable locally defined
global variable locally defined
%% Cell type:code id: tags:
``` python
delta=0
defadd_1_to_delta():
globaldelta
# global variable modified in a function
delta+=1
foriinrange(4):
add_1_to_delta()
print(delta,end=', ')
```
%%%% Output: stream
1, 2, 3, 4,
%% Cell type:markdown id: tags:
## Function Arguments
You can call a function by using the following types of formal arguments:
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
%% Cell type:markdown id: tags:
### Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
%% Cell type:code id: tags:
``` python
defmyfunc(arg0,arg1):
"Return the sum of the first argument with twice the second one."
To call the function `myfunc`, you definitely need to pass two arguments, otherwise it gives a syntax error.
%% Cell type:markdown id: tags:
### Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, Python identifies the arguments by the parameter name.
%% Cell type:code id: tags:
``` python
myfunc(arg1=3,arg0=2)
```
%%%% Output: stream
arg0 + 2*arg1 = 2 + 2*3 = 8
%%%% Output: execute_result
8
%% Cell type:markdown id: tags:
### Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.
%% Cell type:code id: tags:
``` python
defmy_count(arg0,elem=None):
"""return the number of elem in arg0 if elem is None, else