-
PYTHON > les tests, if, elif, else
GENERALITES
if b > a : print("b est plus grand que a")
a == b - a != b - a < b - a <= b - a > b - a >= b
if … elif … else
if b > a: print("b plus grand que a") elif a == b: print("a et b sont égaux")
if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")
FORME COURTE
if a > b: print("a est plus grand que b")
if … else
print("A") if a > b else print("B") print("A") if a > b else print("=") if a == b else print("B")
a = '123' if b else '456'
<condition> ? <expression1> : <expression2>
expression1 if <condition> else <expression2>
D’abord ça évalue la <condition>, si True, <expression1> sera retournée, sinon, ce sera <expression2>
Evaluation is lazy, so only one expression will be executed.
age = 15 print('ado' if age < 18 else 'adulte') # les conditions sont évaluées de gauche à droite ado
age = 15 print('kid' if age < 13 else 'teenager' if age < 18 else 'adult') teenager age = 15 print(('adult', 'kid')[age < 20]) # Selecting an item from a tuple kid print(('adult', 'kid')[True]) kid print({True: 'kid', False: 'adult'}[age < 20]) kid
The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:
>>> age = 15 >>> print((lambda: 'kid', 'lambda: adult')[age > 20]()) kid
age = 15 print(((age < 20) and ['kid'] or ['adult'])[0]) kid
OU - ET
if a > b and c > a: print("Both conditions are True")
if a > b or a > c: print("At least one of the conditions is True")
—
VOIR : https://www.w3schools.com/python/python_conditions.asp
—
toto = true if toto:
EXEMPLES
Tester si nombre est pair
if nombre % 2 == 0:
Tester si un caractère est présent dans un texte
if lettre in 'abcdef':
if lettre not in '!@#$%^&*()_+[]{}' and x is not chr(10):
—