« Programmation Python/Booléens » : différence entre les versions

Contenu supprimé Contenu ajouté
Ligne 118 :
</source>
 
Explications : les valeurs booléennes d'une variable "x" peut être obtenue avec <code>bool(x)</code>.
When the Python interpreter looks at an <code>or</code> expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. This is because for an <code>or</code> expression, the whole thing is true if one of the values is true; the program does not need to bother with the second statement. On the other hand, if the first value is evaluated as false Python checks the second half and returns that value. That second half determines the truth value of the whole expression since the first half was false. This "laziness" on the part of the interpreter is called "short circuiting" and is a common way of evaluating boolean expressions in many programming languages.
 
Similarly, for an <code>and</code> expression, Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise if the first value is true it checks the second and returns that value.
 
One thing to note at this point is that the boolean expression returns a value indicating <code>True</code> or <code>False</code>, but that Python considers a number of different things to have a truth value assigned to them. To check the truth value of any given object <code>x</code>, you can use the fuction <code>bool(x)</code> to see its truth value. Below is a table with examples of the truth values of various objects:
 
{| class="wikitable"
|-
!True !! False
|-
|True || False
|-
|1 || 0
|-
|Numbers otherNombre than zeropositif ||The string 'None'
|-
| Chaine non vide || Chaine vide
|Nonempty strings ||Empty strings
|-
| Liste non vide || Liste vide
|Nonempty lists ||Empty lists
|-
| Dictionnaire non vide || Dictionnaire vide
|Nonempty dictionaries ||Empty dictionaries
|}