1.1. Variables et types#

Il y a différents types classiques : int, float, complex, str… Afin de connaître le type d’une variable, on peut utiliser la fonction type. Python utilise un typage dynamique fort : les variables sont typées, mais, sauf précision contraire, le typage est déterminé automatiquement. Le type d’une variable peut être adapté dynamiquement en fonction des instructions.

Exemple :

a = 1        # a est un entier (integer) egale à 1
print(type(a))
a = 0.1 * a  # a est converti (cast) en nombre decimal (float) approchant 0.1
print(type(a))
<class 'int'>
<class 'float'>

1.1.1. Les entiers#

Les entiers peuvent être représentés par des objets de type int. En python, il n’y a pas de plus grand entier, c’est-à-dire que la taille de la boîte qui stocke un entier peut être aussi grande que la place libre dans l’ordinateur…

Voici un petit code pour exemple :

a = 1
print(type(a))
b = 1000
b = b ** b  # b vaut 1000 ^ 1000 = 10^3000
print(b)
<class 'int'>
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
b = b*1.
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Cell In[3], line 1
----> 1 b = b*1.

OverflowError: int too large to convert to float

1.1.2. Les réels#

On peut représenter les nombres réels par des objets de type float. Il y a donc un plus grand réel que peut supporter la machine, ainsi qu’un plus petit réel supérieur à 0 !

Attention les calculs ne sont pas exacts !

a = 1.
print(type(a))
<class 'float'>

Il est possible de définir un entier en utilisant une notation classique de type ingénieur :

# erreur en utilisant des floats
a = 1.e15
b = a+1
print(b)
a = 1.e16
b = a+1
print(b)

# exact quand on prend des entiers
a = 10000000000000000
b = a+1
print(b)
1000000000000001.0
1e+16
10000000000000001

1.1.3. Les booléens#

La notion de booléens est une notion essentielle en informatique. Cela correspond à une variable qui peut prendre deux états : vrai et faux. En python les booléens sont True et False.

Ils sont souvent utilisés en combinaison des tests.

vrai, faux = True, False
print(type(vrai))
print(type(faux))
<class 'bool'>
<class 'bool'>

Les opérations sur les booléens correspondent aux opérations logiques :

  • et correspond à l’opérateur and

  • ou correspond à l’opérateur or

  • non correspond à l’opérateur not

print(vrai and faux)
print(vrai or faux)
print(not vrai)
print(not faux)
False
True
False
True

On rappelle les règles élémentaires

  • non (A ou B) = (non A) et (non B)

  • non (A et B) = (non A) ou (non B)

print(not (vrai or faux))
print(not (vrai and faux))
False
True

Il est possible de créer des booléens à partir des opérateurs de comparaison. Par exemple

x = 1
y = 1.0
print(x == y)  # opérateur d'égalité
True
x, y = 1, 2
print(x > y)   # opérateur supérieur
print(x != y)  # opérateur de différence
False
True

Exercice

Afin de visualiser un problème de tous les calculs faits par un ordinateur, exécutez la suite d’instructions suivantes :

  • affectez 0.1 à une variable appelée x

  • ajoutez 0.2 à la variable x

  • affectez 0.3 à une variable appelée y

  • affichez les variables x et y puis le booléen x==y

Que remarquez-vous ?

x = 0.1
x = x + 0.2
y = 0.3
print(x, y, x == y)
Hide code cell output
0.30000000000000004 0.3 False

1.1.4. Les chaînes de caractères#

Les chaînes de caractères peuvent être représentées par des objets de la classe str. Elles sont vues comme des listes de caractères et toutes les opérations sur les listes s’appliquent aux objets de type str.

Il y a un certain nombre de fonctions supplémentaires qui peuvent être bien pratiques…

help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |      
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |  
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |  
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |      
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |  
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |      
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |  
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |      
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |  
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |      
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |  
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |      
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |  
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |      
 |      Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
 |      such as "def" or "class".
 |  
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |      
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |  
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |      
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |  
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |      
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |  
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |      
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |  
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |      
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |  
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |      
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |  
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |      
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |      
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |  
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |  
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |  
 |  removeprefix(self, prefix, /)
 |      Return a str with the given prefix string removed if present.
 |      
 |      If the string starts with the prefix string, return string[len(prefix):].
 |      Otherwise, return a copy of the original string.
 |  
 |  removesuffix(self, suffix, /)
 |      Return a str with the given suffix string removed if present.
 |      
 |      If the string ends with the suffix string and that suffix is not empty,
 |      return string[:-len(suffix)]. Otherwise, return a copy of the original
 |      string.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the substrings in the string, using sep as the separator string.
 |      
 |        sep
 |          The separator used to split the string.
 |      
 |          When set to None (the default value), will split on any whitespace
 |          character (including \\n \\r \\t \\f and spaces) and will discard
 |          empty strings from the result.
 |        maxsplit
 |          Maximum number of splits (starting from the left).
 |          -1 (the default value) means no limit.
 |      
 |      Splitting starts at the end of the string and works to the front.
 |  
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the substrings in the string, using sep as the separator string.
 |      
 |        sep
 |          The separator used to split the string.
 |      
 |          When set to None (the default value), will split on any whitespace
 |          character (including \\n \\r \\t \\f and spaces) and will discard
 |          empty strings from the result.
 |        maxsplit
 |          Maximum number of splits (starting from the left).
 |          -1 (the default value) means no limit.
 |      
 |      Note, str.split() is mainly useful for data that has been intentionally
 |      delimited.  With natural text that includes punctuation, consider using
 |      the regular expression module.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |  
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |      
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |  
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |      
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |      
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |  
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |  
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |      
 |      The string is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(...)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.
message = "voici un message très important à lire"
print(message)
print(message.capitalize())  # first character upper case and the rest lower case
print(message.center(80))    # center message in a string of size 80
print(message.find('i'))     # the substring 'i' is in index 2
print(message.find('z'))     # z is not in the string
voici un message très important à lire
Voici un message très important à lire
                     voici un message très important à lire                     
2
-1
print(message.isdecimal())    # can the string be viewed as a decimal number
print("1234654".isdecimal())
print("1234654".zfill(80))    # fill with 0 to have a size of 80
print(int("12345654"))        # convert the string into an integer (if possible)
False
True
00000000000000000000000000000000000000000000000000000000000000000000000001234654
12345654

1.1.5. Les listes et les tuples#

Les listes et les tuples permettent de stocker plusieurs objets (pas forcément du même type). La différence essentielle est que les listes sont mutables (il est possible de modifier les objets de la liste) alors que les tuples sont non mutables (il est impossible de modifier les objets du tuple).

La fonction len() permet de récupérer la taille de la liste et l’opérateur [] permet d’avoir accès (de lire et éventuellement d’écrire) aux éléments.

La fonction append permet d’ajouter un élément à la liste. Les opérateurs +, * sont également utilisables sur les listes pour concaténer.

t = (0, 1, 2, "toto", "titi", [0, 1, 2])
print(type(t))
print(t)
print(t[0])
t[0] = 1
print(t)
<class 'tuple'>
(0, 1, 2, 'toto', 'titi', [0, 1, 2])
0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[15], line 5
      3 print(t)
      4 print(t[0])
----> 5 t[0] = 1
      6 print(t)

TypeError: 'tuple' object does not support item assignment
# ATTENTION TOUTEFOIS, ON PEUT FAIRE DES TRUCS BIZARRE
print(t[5])
t[5][0] = 'z'
print(t)
[0, 1, 2]
(0, 1, 2, 'toto', 'titi', ['z', 1, 2])
l = [0, 1, 2, "toto", "titi"]
print(l)
print(l[0])
l[0] = t
print(l)
[0, 1, 2, 'toto', 'titi']
0
[(0, 1, 2, 'toto', 'titi', ['z', 1, 2]), 1, 2, 'toto', 'titi']
t = (0, 1, 2, 3, 4)
l = list(t)
print(l)
ll = l + l
print(ll)
l2 = l * 2
print(l2)
print("-"*80)
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
--------------------------------------------------------------------------------

Il est possible d’avoir accès à plusieurs éléments d’un coup à l’aide des :.

l = [0, 1, 2, 3, 4, 5, 6]
debut_l = l[:3]
fin_l = l[3:]
print(debut_l)
print(fin_l)
print(debut_l + fin_l)

# nous avons fait des copies !!!
debut_l[0] = 10
print(debut_l)
print(l)

# on peut parcourir dans l'autre sens
print(l[::-1])

# on peut parcourir de 2 en 2 et aussi à l'envers
print(l[::2])
print(l[-1::-2])
[0, 1, 2]
[3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[10, 1, 2]
[0, 1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1, 0]
[0, 2, 4, 6]
[6, 4, 2, 0]
l = list(range(10))
print(l)
begin, end, step = 1, 5, 2
print(l[begin:end:step])
# 0 1 2 3 4 5 6 7 8 9
#   1   3
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3]

1.1.6. Compréhension de listes#

Python offre des fonctions très intéressantes et très puissantes pour traiter les listes : la compréhension de liste. La syntaxe est la suivante :

nouvelle_liste = [
    fonction(element) for element in liste if condition(element)
]
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[lk for lk in l if lk % 2 == 0]
[0, 2, 4, 6, 8]
[lk**2 for lk in l]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[lk%2 * lk**2 for lk in l if lk%3]
[1, 0, 0, 25, 49, 0]

Exercice

Créez la liste des puissances de \(2\) de \(2^0\) à \(2^9\) en utilisant la compréhension de liste.

Hide code cell source
[2**k for k in l]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]