# Question About Logic In Python

mensanator at aol.com mensanator at aol.com
Mon Sep 19 04:01:30 CEST 2005

```James H. wrote:
> Greetings!  I'm new to Python and am struggling a little with "and" and
> "or" logic in Python.  Since Python always ends up returning a value
> and this is a little different from C, the language I understand best
> (i.e. C returns non-zero as true, and zero as false), is there anything
> I should be aware of given Python's different approach?  Namely any
> pitfalls or neat tricks that make the Python approach cool or save my
> butt.
>
> Thank you!
>
> James

Booleans are a subtype of plain integers, so if you use them
in arithmetic expressions, they evaluate to 0 and 1.

>>> def bool():
print "Boolean algebra"
print "%9s %9s | %9s %9s %9s" % ('A','B','A and B','A or B','A xor B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s"  % (a,b,(a and b),(a or b),((a and not
b) or (not a and b)))
print
print
print "Arithmetic"
print "%9s %9s | %9s %9s %9s" % ('A','B','A + B','A * B','A - B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s"  % (a,b,(a + b),(a * b),(a - b))

>>> bool()
Boolean algebra
A         B |   A and B    A or B   A xor B
---------------------------------------------------
False     False |     False     False     False
False      True |     False      True      True
True     False |     False      True      True
True      True |      True      True     False

Arithmetic
A         B |     A + B     A * B     A - B
---------------------------------------------------
False     False |         0         0         0
False      True |         1         0        -1
True     False |         1         0         1
True      True |         2         1         0

```