[Tutor] mnemonics to better learn Python
Dave Angel
davea at ieee.org
Fri Jul 31 19:51:30 CEST 2009
Eduardo Vieira wrote:
> <snip>
>
> Hello, would anybody have a good memorization technique for boolean
> results? Like when using 'or'/'and' what it returns when both are
> false, the last is false, etc?
> I find it so hard to remember that...
> Eduardo
>
>
I don't blame you for finding it hard to remember. The English language
(and probably most others, but I wouldn't know) lets people abuse these
meanings, but programming insists you get it right.
If you think of 0 for False, and 1 for True, then
or is plus a sum is nonzero if a is 1 or if b is
1 (or both)
and is times a product is only nonzero if both a and
b are 1
xor is minus a difference is zero only if a is the
same as b (both True, or both False)
In simple electrical circuitry, 'or' is switches in parallel, 'and'
is switches in series.
In programming terms, and is nested ifs, while or is two ifs at the
same level, either of which does the same thing.
def and(a, b):
if a:
if b:
print "this is the and of the two"
return True
else:
return False
def or(a, b):
if a:
print "this is the or"
return True
if b:
print "this is the or"
return True
return False
DaveA
More information about the Tutor
mailing list