Fonctions

by Christian Nguyen, Joseph Razik, on 2019-10-18
fonctions

Paramètres de fonction et paramètres par défaut

In [1]:
def f1(x, y=1, z=2):
    print('x = ', x, ', y = ', y, ' z = ', z)
In [2]:
f1(0)
f1(0, 0)
f1(0, 0, 0)
x =  0 , y =  1  z =  2
x =  0 , y =  0  z =  2
x =  0 , y =  0  z =  0
In [3]:
f1(0, z=0)
f1(y=-2, z=-1, x=-3)
x =  0 , y =  1  z =  0
x =  -3 , y =  -2  z =  -1
In [4]:
def f2(mesg, rep=('o', 'O', 'n', 'N')):
    choix = ''
    while choix not in rep:
        print("La reponse doit etre dans " + str(rep))
        choix = input(mesg)
    return choix
In [5]:
f2('Continuer ? ')
La reponse doit etre dans ('o', 'O', 'n', 'N')
Continuer ? o
Out[5]:
'o'

Nombre de paramètres variables

In [6]:
def f3(*args):
    # args est une liste
    print('appel avec', len(args), ' parametre(s)')
    for p in args:
        print(p)
In [7]:
f3('a')
f3(250, 130, 0)
appel avec 1  parametre(s)
a
appel avec 3  parametre(s)
250
130
0
In [8]:
def f4(**kwargs):
    # kwargs est un dictionnaire
    print('appel avec', len(kwargs), ' parametre(s)')
    for k in kwargs:
        print('kwargs[' + str(k) + '] = ' + str(kwargs[k]))
In [9]:
f4(r=250, v=130, b=0)
appel avec 3  parametre(s)
kwargs[r] = 250
kwargs[b] = 0
kwargs[v] = 130
In [10]:
dico1 = {'r': 250, 'v': 130, 'b': 0}
f4(**dico1)
appel avec 3  parametre(s)
kwargs[r] = 250
kwargs[b] = 0
kwargs[v] = 130
In [11]:
def f5(a, b, c):
    print(a, b, c)
In [12]:
tuple1 = ('a', 'b', 'c')
try:
    f5(tuple1)
except TypeError:
    print('erreur de type : il manque 2 parametres')
erreur de type : il manque 2 parametres
In [13]:
f5(*tuple1)
a b c

Signature de fonction

In [14]:
def f():
    """ fonction f sans paramètre. """
    pass
In [15]:
def f(a, b):
    """ fonction f avec deux paramètres. """
    pass
In [16]:
whos
Variable   Type        Data/Info
--------------------------------
dico1      dict        n=3
f          function    <function f at 0x7ff0b8378840>
f1         function    <function f1 at 0x7ff0b83616a8>
f2         function    <function f2 at 0x7ff0b8361e18>
f3         function    <function f3 at 0x7ff0b8361f28>
f4         function    <function f4 at 0x7ff0b8361840>
f5         function    <function f5 at 0x7ff0b8361598>
tuple1     tuple       n=3
In [17]:
import pocketnoobj
Initialisation de l'espace de nommage fait.
In [18]:
count(dir(), 'f')
Out[18]:
1
In [19]:
help(f)
Help on function f in module __main__:

f(a, b)
    fonction f avec deux paramètres.

In [20]:
try:
    f()
except TypeError as e:
    print('Error: ', e)
Error:  f() missing 2 required positional arguments: 'a' and 'b'