\makeatletter
\@ifundefined{complet}
{\documentclass[10pt]{report}
\title{Python}
\newcommand{\categorie}{Python}
\input{latex_entete_perso}

\begin{document} %Cours

\setcounter{chapter}{3}
% xelatex --shell-escape cours_python
}
{}
\makeatother

\IfFileExists{mm_principe.png}{}{\write18{wget https://doc.infoforall.fr/activite/python/images/dictionnaire/mm_principe.png}}

\IfFileExists{string_principe.png}{}{\write18{wget https://doc.infoforall.fr/activite/python/images/string/string_principe.png}}

\chapter{Types simples}

\section{Nombres : int et float}

\begin{multicols}{2}


\subsection{Encoder une information}

\remarque{Encoder} une information veut dire qu'on transforme notre information en \remarque{séquence de 0 et de 1} en respectant une \remarque{technique d'encodage} précise. Si on connaît la technique d'encodage, on peut \remarque{décoder}.

\small{
Information -> ENCODAGE -> 010101011100...
}



\small{
010101011100... -> DECODAGE -> Information
}



\subsection{Integers}

Les \gras{entiers} sont encodés sous forme d'\remarque{integer}. 
Nommé \formule{\gras{int}} en Python. La fonction native \formule{\gras{type()}} indique le type.

\begin{multicols}{2}

\small{
\begin{minted}{bat}
>>> type(5)
<class 'int'>
\end{minted}
}

\small{
\begin{minted}{bat}
>>> type(5.0)   
<class 'float'>
\end{minted}
}

\end{multicols}

Les \remarque{signatures associées} sont indiquées ci-dessous.

\gras{$\rhd$ Addition} avec \fo{+} : \fo{int + int -> int}

\gras{$\rhd$ Soustraction} avec \fo{-} : \fo{int - int -> int}

\gras{$\rhd$ Multiplication} avec \fo{*} : \fo{int * int -> int}

\gras{$\rhd$ Division} avec \fo{/} : \fo{int / int -> float}

\gras{$\rhd$ Quotient} avec \fo{//} : \fo{int // int -> int}

\gras{$\rhd$ Reste} avec \fo{\%} : \fo{int \% int -> int}

\gras{$\rhd$ Puissance} avec \fo{**} : \fo{int ** int -> int}

\small{
\begin{minted}{python}
>>> 23 / 5
4.6        # Attention au float sur /
\end{minted}
}

\subsection{Floats}

Les \gras{nombres à virgule} sont encodés par le type \gras{\fo{float}}. X symbolisera un opérateur parmi \gras{\fo{+ - * / // \% **}}.
 
\begin{itemize}
\item \fo{float X float -> float}
\item \fo{float X int   -> float}
\item \fo{int   X float -> float}
\end{itemize}

Dès qu'il y a un float en entrée, la signature indique un float en sortie.

\subsection{Le problème des flottants}

\paragraph{Integer}

Les entiers sont \gras{exactement enregistrés}.

\fo{7 -> ENCODAGE -> 00000111 -> DECODAGE -> 7}

\paragraph{Float}

Certains floats sont enregistrés \gras{approximativement}. Lorsqu'on décode, on obtient donc parfois \gras{presque} la valeur.

\fo{0.1 -> ENCODAGE -> 00..010101.. -> DECODAGE -> 0.10000000000000001}


\paragraph{A SAVOIR IMPERATIVEMENT}~: l'encodage des nombres réels en float provoque parfois un enregistrement approximatif de la valeur de départ.

\gras{Conséquence}~: Si on peut faire les calculs en se passant des flottants, on privilégie cette solution.

\gras{Le plus perturbant}~: parfois c'est exact, parfois c'est approximatif. Nous verrons pourquoi dans DONNEES.

\begin{multicols}{2}

\small{
\begin{minted}{python}
>>> 4.8 - 4.2
0.5999999999999996
 
>>> 3 * 0.1
0.30000000000000004

>>> 0.75 - 0.25
0.5
 
>>> 3 * 0.25
0.75
\end{minted}
}

\end{multicols}

Comme vous le voyez, cela provoque \gras{parfois} des erreurs de calculs. Avec plusieurs milliards d'approximations par seconde, on peut obtenir rapidement des erreurs énormes.

\end{multicols}


\section{Texte : string (str)}

\begin{multicols}{2}

\subsection{Définition}

Le \remarque{string} est un conteneur formant une collection ordonnée de caractères.

\begin{tabular}{cccccccc}
\hline
   Indice & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\
   Caractère & 'B' & 'o' & 'n' & 'j' & 'o' & 'u' & 'r' \\
\hline
\end{tabular}

\remarque{Première case 0} : avec 7 cases, les indices vont de 0 à 6.

\gras{Indice} se traduit par \gras{index} en anglais.

\begin{figure}[H]
\centering
\includegraphics[height=3cm]{string_principe.png}
\caption{Principe du string}
\label{Principe-string}
\end{figure}

String est un mot anglais qui signifie chaîne : un texte est un ensemble de caractères qui se suivent. Exemple avec le mot \fo{Bonjour}~:








\subsection{Déclaration avec Python}

Les strings sont gérés par le type \gras{\fo{str}}.

\subsubsection{Déclaration}

Un string Python est délimité par deux indicateurs signalant le début et la fin du string. Cet indicateur peut être :

\begin{itemize}
\item un guillemet simple : \fo{'Bonjour'} (touche du 4)
\item trois guillemets simples : \fo{'''Bonjour'''}
\item un guillemet double : \fo{"Bonjour"} (touche du 3)
\item trois guillemets doubles : \fo{"""Bonjour"""}
\end{itemize}
    
Jamais de mélange pour un même string : si on commence avec un double, on finit avec un double.

\small{
\begin{minted}{python}
    >>> "Hello World !'
      File "", line 1
        "Hello World !'
                      ^
    SyntaxError: EOL while scanning string literal
\end{minted}
}
    
Python répond toujours avec des guillemets simples lorsqu'il le peut.
     

\subsubsection{Déclaration d'un string multi-ligne}

On peut déclarer un string intégrant des passages à la ligne (celles intégrant des appuis sur ENTREE) en utilisant 3 guillemets :

\small{
\begin{minted}[linenos=true, bgcolor=lightgray, tabsize=4, gobble=0, fontfamily=courier, fontsize=\small, xleftmargin=20pt, xrightmargin=5pt]{python}
s = """Voici une liste :
- premier truc
- deuxième truc
- troisième truc
 
En ici, c'est fini"""
 
print(s)
\end{minted}
}

Voici l'affichage obtenu dans la console :

\small{
\begin{minted}{bat}
Voici une liste :
- premier truc
- deuxième truc
- troisième truc

En ici, c'est fini
\end{minted}
}


\subsubsection{Déclaration d'un string vide}

Deux solutions :

\begin{multicols}{2}

\small{
\begin{minted}{python}
>>> s = ""
>>> s
''
 
>>> s = str()
>>> s
''
\end{minted}
}

\end{multicols}

\subsection{Opérateurs Python}

\gras{$\rhd$ Concaténation} avec \fo{+} : \fo{str + str -> str}

La concaténation correspond à une sorte d'addition, mais la mécanique utilisée est celle d'un juxtaposition. D'où l'utilisation d'un autre terme.

\begin{multicols}{2}
\small{
\begin{minted}{python}
>>> "bon" + "jour"
'bonjour'

>>> '5' + '5'
'55'
\end{minted}
}
\end{multicols}

\small{
\begin{minted}{python}
>>> 'Bonj' + 5
TypeError: can only concatenate str to str
\end{minted}
}


\gras{$\rhd$ Répétitition} avec \fo{*} : 

\begin{itemize}
\item \fo{int * str -> str}
\item \fo{str * int -> str}
\end{itemize}


La répétition correspond à une sorte de copier-coller d'un string.

\begin{multicols}{2}
\small{
\begin{minted}{python}
>>> "Bon" * 2
'BonBon'
 
>>> 4 * "Pom ! "
'Pom ! Pom ! Pom ! Pom ! '
\end{minted}
}
\end{multicols}

\small{
\begin{minted}{python}
>>> '#' * 20
'####################'
\end{minted}
}

\gras{$\rhd$ Les autres ?} : les autres opérateurs ne sont pas implémentés sur les strings. Leur utilisation avec un string provoque donc une erreur.

\subsection{Déterminer sa longueur}

La longueur d'un string correspond au nombre de "cases-caractères" du string. 
On utilise la fonction native \gras{\formule{len()}}.

\small{
\begin{minted}{python}
Indice     0123456 
>>> mot = "Bonjour"
>>> len(mot)
7
\end{minted}
}

Il y a 7 caractères, on sait alors qu'on peut demander des indices allant de 0 à ...6.

\end{multicols}




\section{Propriété : bool}

\begin{multicols}{3}

\paragraph{Propriété}
affirmation qui peut être vraie ou fausse.

\subsubsection{Booléens}

Lorsqu'on utilise certains opérateurs booléens, l'interpréteur évalue votre expression en répondant \fo{True} si c'est vrai, \fo{False} sinon.

\subsubsection{Opérateurs renvoyant un booléen}

\gras{$\rhd$ Strictement supérieur} \fo{>} : 

Python gére cet opérateur avec des nombres, des strings...

\small{
\begin{minted}{python}
>>> 40 > 30
True

>>> "crocodile" > "tortue"
False
\end{minted}
}

On utlise l'ordre lexicographique (du dictionnaire si tout en minuscule). 

\gras{$\rhd$ Egalité} avec \fo{==}

\small{
\begin{minted}{python}
>>> 40 == 3 * 10
False

>>> 40 == 4 * 10
True

>>> 0.3 == 3 * 0.1
False
\end{minted}
}


\gras{$\rhd$ Différence} avec \fo{!=}

\small{
\begin{minted}{python}
>>> 40 != 3 * 10
True

>>> 40 != 4 * 10
False
\end{minted}
}

\gras{$\rhd$ Autres opérateurs de comparaison}
\begin{itemize}
\item Supérieur ou égal \fo{>=}
\item Inférieur ou égal \fo{<=}
\end{itemize}

\

\gras{$\rhd$ Appartenance avec \fo{\gras{in}}}

Le mot-clé \fo{\gras{in}} permet de savoir si un élément \fo{\gras{a}} est présent dans un élément \fo{\gras{b}}~: \fo{\gras{a in b}}

\small{
\begin{minted}{python}
>>> "soja" in composition
False
\end{minted}
}

\end{multicols}


\section{Transtyper : passer d'un type à un autre}


\begin{multicols}{4}

\small{
\begin{minted}{python}
# 4.4.1 VIDE

>>> i = int()
>>> i = 0

>>> f = float()
>>> f = 0.0

>>> s = str() 
>>> s = ''

>>> b = bool()
>>> b = False


# 4.4.3 FLOAT

>>> f = float("5")
>>> f
5.0
 
>>> f = float("5.2")
>>> f
5.2
 
>>> f = float("")
ValueError
\end{minted}

\columnbreak

\begin{minted}{python}
# 4.4.2 INTEGER

>>> i = int(5)
>>> i
5
 
>>> i = int(5.2)
>>> i
5
 
>>> i = int("5")
>>> i
5

>>> i = int("5.2")
ValueError
 
>>> i = int("")
ValueError
 
>>> i = int(False)
>>> i
0
 
>>> i = int(True)
>>> i
1
\end{minted}

\columnbreak 

\begin{minted}{python}
# 4.4.4 STRING 

>>> s = str(5)
>>> s
'5'
 
>>> s = str(5.2)
>>> s
'5.2'
 
>>> s = str(False)
>>> s
'False'
 
>>> s = str(True)
>>> s
'True'
\end{minted}

\columnbreak 

\begin{minted}{python}
# 4.4.5 BOOLEEN

>>> b = bool(0)
>>> b
False
 
>>> b = bool(5)
>>> b
True
 
>>> b = bool(5.2)
>>> b
True


# 4.4.6 CLAVIER

>>> n = int(input())

>>> n = float(input())
\end{minted}

}

\end{multicols}



\paragraph{A SAVOIR PAR COEUR}
Un contenu VIDE/NUL est évalué à \gras{\fo{False}} si on veut un booléen. Sinon, c'est \gras{\fo{True}}.




\input{licence}

\makeatletter
\@ifundefined{complet}
{\end{document}}

{}
\makeatother

