dketov
12/12/2011 - 1:31 PM

Логические операции

Логические операции

# -*- encoding: utf-8 -*-
"""
Простейший селектор
"""

a = "first" 
b = "second" 
print 1 and a or b

print 0 and a or b

# evaluated from left to right, so the and is evaluated first. 

# 0 and 'first' evaluates to False, and then 0 or 'second' evaluates to 'second'.
# -*- encoding: utf-8 -*-
"""
Использование логических операций
"""

t, f = 1, 0
x, y = 88, 99

a = (t and x) or y           # if true, x
print a

a = (f and x) or y           # if false, y
print a

print ((t and [x]) or [y])[0]     # if true, x

print ((f and [x]) or [y])[0]     # if false, y

print (t and f) or y              # fails: f is false, skipped

print ((t and [f]) or [y])[0]     # works: f returned anyhow
# -*- encoding: utf-8 -*-
"""
Логическое ИЛИ
"""

print 'a' or 'b'                                         

print '' or 'b'                                          

print '' or [] or {}                                     

def sidefx(): 
     print "in sidefx()" 
     return 1 
'a' or sidefx()                       
# -*- encoding: utf-8 -*-
"""
Логическое И
"""

print 'a' and 'b'

print '' and 'b' 

print 'a' and 'b' and 'c'