Noms et variables

Utiliser des variables pour être plus flexible

La même instruction, print(a * 2) , donne différents résultats selon la valeur de a.

-> séparation entre opérations et données

[1]:
a = 'to'
print(a * 2)

a = 'ta'
print(a * 2)

a = 21
print(a * 2)
toto
tata
42

Un même nom peut être utilisé successivement pour différentes variables/valeurs sans contrainte de type.

Utiliser un nom inconnu est difficile

[2]:
inconnu
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 inconnu

NameError: name 'inconnu' is not defined
[3]:
inconnu = 'XXX'
inconnu
[3]:
'XXX'

Qu’est-ce qu’un nom licite ?

Il utilise seulement les caractères suivants

  • underscore : _

  • lettres minuscules : [a-z]

  • lettres majuscules : [A-Z]

  • nombres : [0-9]

MAIS il ne commence pas par un nombre ([0-9])

[4]:
# exemples qui marchent

x = 2

camion = 'vroum'

HAUT = 'O'

unnomlongmaispaslisible = 0

un_nom_long_lisible = 1

UnNomLongAussiLisible = 2

_avec_une_patte_devant = 3

__avec_des_longues_pattes_partout__ = 4
[5]:
# exemple qui marche pas
allo? = 3
  Cell In[5], line 2
    allo? = 3
        ^
SyntaxError: invalid syntax

[6]:
# exemple qui marche pas
deux-nom = 3
  Cell In[6], line 2
    deux-nom = 3
    ^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

[7]:
# exemple qui marche pas
0_commence_avec_zero = False
  Cell In[7], line 2
    0_commence_avec_zero = False
     ^
SyntaxError: invalid decimal literal

De plus, Il ne doit pas être déjà réservé par le langage

[8]:
from keyword import kwlist

width = 6

print(f'Voici les {len(kwlist)} mots-clefs de Python:\n')

for i in range(0, len(kwlist), width):
    for word in kwlist[i:i + width]:
        print('-', word.ljust(12), end=' ')
    print()

Voici les 35 mots-clefs de Python:

- False        - None         - True         - and          - as           - assert
- async        - await        - break        - class        - continue     - def
- del          - elif         - else         - except       - finally      - for
- from         - global       - if           - import       - in           - is
- lambda       - nonlocal     - not          - or           - pass         - raise
- return       - try          - while        - with         - yield
[9]:
lambda = 123
  Cell In[9], line 1
    lambda = 123
           ^
SyntaxError: invalid syntax

[10]:
lambda_ = 123

Extra

[11]:
# Attention : 'int', 'float', 'str' ne sont pas réservés !
print(int(3.14))
int = 'oups'
print(int(3.14))
3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 4
      2 print(int(3.14))
      3 int = 'oups'
----> 4 print(int(3.14))

TypeError: 'str' object is not callable
[12]:
int = type(1)  # un moyen de restaurer 'int'

Exercice

Jouer un peu avec les opérateurs +, *

Essayer un exemple concret avec la conversion de température °C/°F de formule $ Celsius = :nbsphinx-math:frac{5}{9}`(Fahrenheit - 32) $ <https://fr.wikipedia.org/wiki/Degr%C3%A9_Fahrenheit>`__.

Expérimenter l’utilisation du print(nom) pour voir le résultat de quelques calculs.