Zanurkuj w Pythonie/Operatory and i or: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Rofrol (dyskusja | edycje)
mNie podano opisu zmian
Rofrol (dyskusja | edycje)
mNie podano opisu zmian
Linia 49:
# 0 and 'first' daje fałsz, a potem 0 or 'second' daje 'second'.
 
Jakkolwiek to wyrażenie Pythona jest po prostu logiką boolowską, a nie specjalną konstrukcją języka, istnieje jedna bardzo ważna różnica pomiędzy tą sztuczką and-or w Pythonie a składnią bool ? a : b w C. Jeśli wartość a jest fałszem, wyrażenie nie będzie działało jak mógłbyś oczekiwać. (CanCzy younaciąłem tellsię Ina wasto? bitten by this?Więcej Moreniż thanjeden onceraz?)
 
 
'''Przykład 4.18. WhenKidy thezawodzi sztuczka and-or Trick Fails'''
 
>>> a = ""
Linia 59:
'second'
 
# SinceJako aże isa anjest emptypustym stringnapisem, whichktóry Python considersuważa falsejako infałsz aw booleankontekście contextlogicznym, 1 and '' evalutes todaje '', and thennastępnie '' or 'second' evalutes todaje 'second'. OopsUups! That'sTo notnie whatto youco wantedchciałeś.
 
TheSztuczka and-or trick, bool and a or b, willnie notbędzie workdziałała likejak thewyrażenie C expression bool ? a : b whenkiedy a isjest falsefałszem in aw booleankontekście contextlogicznym.
 
ThePrawdziwą realsztuczką trickkryjącą behindsię theza sztuczką and-or trick, then,jest isupewnienie tosię, makeże surewartość thata the value of anigdy isnie neverjest falsefałszywa. One common way of doing this is to turn a into [a] and b into [b], then taking the first element of the returned list, which will be either a or b.
Example 4.19. Using the and-or Trick Safely