Created
December 12, 2011 13:31
-
-
Save dketov/1467154 to your computer and use it in GitHub Desktop.
Логические операции
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
""" | |
Логическое И | |
""" | |
print 'a' and 'b' | |
print '' and 'b' | |
print 'a' and 'b' and 'c' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
""" | |
Логическое ИЛИ | |
""" | |
print 'a' or 'b' | |
print '' or 'b' | |
print '' or [] or {} | |
def sidefx(): | |
print "in sidefx()" | |
return 1 | |
'a' or sidefx() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment