Operatori logici
Aggregazione dei criteri
Ricevere una valutazione
Ottenere la sufficienza
Funzionamento degli operatori logici
A differenza di altri linguaggi, in Python gli operatori and e or non restituiscono sempre semplicemente True o False, ma restituiscono uno degli operandi coinvolti, a seconda del loro valore di verità.
Il concetto è quello di restituire il primo operatore che determina il risultato dell'espressione tralasciando la valutazione dei successivi. Questo concetto si chiama valutazione short-circuit.
Operatore and
| Scenario | Regola | Risultato (Valore restituito) | Esempio |
|---|---|---|---|
| Falsy and ... | Restituisce immediatamente il primo operando (che è Falsy) in quanto qualsiasi valore messo in and con un False darà come risultato False. | Primo Operando | 0 and
5 restituisce 0 |
| Truthy and Falsy | Restituisce il secondo operando (che è Falsy). | Secondo Operando | "A" and
False restituisce False |
| Truthy and Truthy | Restituisce il secondo operando. | Secondo Operando | 10 and
"B" restituisce "B" |
Operatore or
L'operatore or restituisce il primo valore Truthy di una espressione.
| Scenario | Regola | Risultato (Valore restituito) | Esempio |
|---|---|---|---|
| Truthy and ... | Restituisce immediatamente il primo operando (che è Truthy) in quanto qualsiasi valore messo in or con un True darà come risultato True. | Primo Operando | "A" or 5 restituisce "A" |
| Falsy or Truthy | Restituisce il secondo operando (che è Truthy). | Secondo Operando | 0 or
True restituisce True |
| Falsy and Falsy | Restituisce il secondo operando. | Secondo Operando | "" or
0.0 restituisce 0.0 |
Operatore not
L'operatore not è l'unico operatore logico che restituisce sempre un valore Booleano (True o False).
| Regola | Descrizione | Esempio |
|---|---|---|
| not Truthy | Restituisce sempre False |
not 10 restituisce False |
| not Falsy | Restituisce sempre True |
not "" restituisce True |