Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 12, 2011 13:31
Show Gist options
  • Save dketov/1467154 to your computer and use it in GitHub Desktop.
Save dketov/1467154 to your computer and use it in GitHub Desktop.
Логические операции
# -*- encoding: utf-8 -*-
"""
Логическое И
"""
print 'a' and 'b'
print '' and 'b'
print 'a' and 'b' and 'c'
# -*- 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 -*-
"""
Использование логических операций
"""
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 -*-
"""
Простейший селектор
"""
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