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

Contenu supprimé Contenu ajouté
Ligne 138 :
 
Détails de l'exemple :
<source lang=python>
>>> 'a' == ('a' or 'b') # 'a' = True, comme 'a' = 'a', on n'évalue pas 'b'
>>> 'a' == ('a' or 'b') # 'a' = True, donc ('a' or 'b') = 'a' sans avoir à évaluer 'b'. Ce qui revient à : 'a' == 'a'
True
 
>>> 'ab' == ('a' or 'b') # 'a'Revient = True,à comme: 'ab' == 'a', onde n'évaluela pasmême 'b'manière
Second case:
>>> 'b' == ('a' or 'b') # Look at parentheses first, so evaluate expression "('a' or 'b')"
# 'a' is a nonempty string, so the first value is True
# Return that first value: 'a'
>>> 'b' == 'a' # the string 'b' is not equivalent to the string 'a', so expression is False
False
 
>>> 'a' == ('a' and 'b') # 'a' = True et 'b' = True, donc ('a' and 'b') = 'b'. Ce qui revient à : 'a' == 'b'
Third case:
>>> 'a' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"
# 'a' is a nonempty string, so the first value is True, examine second value
# 'b' is a nonempty string, so second value is True
# Return that second value as result of whole expression: 'b'
>>> 'a' == 'b' # the string 'a' is not equivalent to the string 'b', so expression is False
False
 
>>> 'b' == ('a' and 'b') # Revient à : 'b' == 'b', de la même manière
Fourth case:
>>> 'b' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"
# 'a' is a nonempty string, so the first value is True, examine second value
# 'b' is a nonempty string, so second value is True
# Return that second value as result of whole expression: 'b'
>>> 'b' == 'b' # the string 'b' is equivalent to the string 'b', so expression is True
True
</source>
 
So Python was really doing its job when it gave those apparently bogus results. As mentioned previously, the important thing is to recognize what value your boolean expression will return when it is evaluated, because it isn't always obvious.