Introduction aux fonctions

[1]:
def add(x, y):
    "additionne x et y"
    result = x + y
    return result
[2]:
add(1, 2)
[2]:
3
[3]:
add('bon', 'jour')
[3]:
'bonjour'
[4]:
help(add)
Help on function add in module __main__:

add(x, y)
    additionne x et y

[5]:
a = add(1, 2)
b = add(3, 4)
c = add(a, b)
print(a, b, c)
3 7 10
[6]:
add(1, add(1, add(1, add(1, 1))))
[6]:
5
[7]:
from IPython.display import IFrame
IFrame("https://pythontutor.com/iframe-embed.html#code=def%20add%28x,%20y%29%3A%0A%20%20%20%20%22additionne%20x%20et%20y%22%0A%20%20%20%20result%20%3D%20x%20%2B%20y%0A%20%20%20%20return%20result%0A%0Aa%20%3D%20add%281,%202%29%0Ab%20%3D%20add%28a,%2010%29%0A&codeDivHeight=400&codeDivWidth=350&cumulative=true&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false",
       width='100%', height=400)
[7]:

lien

Fonctions sans retour

[8]:
def ne_renvoie_rien(arg):
    "affiche arg"
    print(arg)

a = ne_renvoie_rien('bonjour')
b = ne_renvoie_rien(42)
print(a, b)
bonjour
42
None None
[9]:
def ne_renvoie_rien_bis(arg):
    "affiche arg"
    print(arg)
    return

a = ne_renvoie_rien_bis('bonjour')
b = ne_renvoie_rien_bis(42)
print(a, b)
bonjour
42
None None

None ?

  • None sert à représenter le rien (ce qui ne sert pas à rien)

  • Il est unique

  • A part sa conversion en booléen (False), il ne fonctionne avec aucun opérateur

  • On teste si une variable est None avec x is None

[10]:
bool(None)
[10]:
False
[11]:
int(None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 int(None)

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
[12]:
None + 0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 None + 0

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Exercices