In Python, le istruzioni if, elif (contrazione di «else and if») ed else servono a controllare il flusso dell'esecuzione e a prendere decisioni all'interno di un programma.
A differenza di molti altri linguaggi di programmazione, le versioni di Python 3.9 e precedenti non offrono un'istruzione formale di tipo case-switch: al suo posto usano più istruzioni elif per ottenere uno scopo simile.
Python 3.10 introduce una variante dell'istruzione case-switch chiamata pattern matching, che tratteremo separatamente in un altro concetto.
Le istruzioni condizionali usano espressioni che devono risolversi in True o False, restituendo direttamente un bool oppure valutando se un valore è «truthy» o «falsy».
x = 10
y = 5
# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
Se abbinato a if, un blocco di codice else opzionale viene eseguito quando la condizione originale di if è False:
x = 5
y = 10
# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
elif consente più valutazioni/rami.
x = 5
y = 10
z = 20
# The elif statement allows for the checking of more conditions.
if x > y > z:
print("x is greater than y and z")
elif y > x > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
Le operazioni booleane e i confronti possono essere combinati con le istruzioni condizionali per test più complessi:
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... say = 'FizzBuzz!'
... elif number % 5 == 0:
... say = 'Buzz!'
... elif number % 3 == 0:
... say = 'Fizz!'
... else:
... say = str(number)
...
... return say
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
In alternativa, l'esempio precedente può essere riscritto usando solo istruzioni if con returns.
Tuttavia, riscrivere in questo modo potrebbe nascondere che le condizioni sono pensate per essere mutuamente esclusive e potrebbe portare a bug futuri o a problemi di manutenzione.
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... return 'FizzBuzz!'
... if number % 5 == 0:
... return 'Buzz!'
... if number % 3 == 0:
... return 'Fizz!'
...
... return str(number)
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
Anche le istruzioni condizionali possono essere annidate.
>>> def driving_status(driver_age, test_score):
... if test_score >= 80:
... if 18 > driver_age >= 16:
... status = "Student driver, needs supervision."
... elif driver_age == 18:
... status = "Permitted driver, on probation."
... elif driver_age > 18:
... status = "Fully licensed driver."
... else:
... status = "Unlicensed!"
...
... return status
>>> driving_status(63, 78)
'Unlicensed!'
>>> driving_status(16, 81)
'Student driver, needs supervision.'
>>> driving_status(23, 80)
'Fully licensed driver.'
Anche se Python non ha un operatore ternario ? specifico, è possibile scrivere conditional expressions su una sola riga.
Queste assumono la forma <value if True> if <conditional test> else <value if False>.
Dato che queste espressioni possono diventare difficili da leggere, si consiglia di usare questa forma su una sola riga solo se accorcia il codice e ne migliora la leggibilità.
>>> def just_the_buzz(number):
... return 'Buzz!' if number % 5 == 0 else str(number)
>>> just_the_buzz(15)
'Buzz!'
>>> just_the_buzz(7)
'7'
In Python, qualsiasi oggetto può essere sottoposto a un test di verità e può quindi essere usato con un'istruzione condizionale, un confronto o un'operazione booleana.
Gli oggetti valutati in questo modo sono considerati «truthy» o «falsy» e vengono usati in un boolean context.
>>> def truthy_test(thing):
... if thing:
... print('This is Truthy.')
... else:
... print("Nope. It's Falsy.")
# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."
>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'
# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."
>>> truthy_test('yes')
'This is Truthy.'
# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."