## Converting Boolean Values¶

We can convert to and from Boolean values in the same way we can convert between, for example, floats and strings:

In [1]:
float("3.14")

Out[1]:
3.14

For the types of values we know: here is the rule for converting to Booleans: anything that's not "" or 0 converts to True, and the empty string "" and 0 convert to False:

In [2]:
bool(0)

Out[2]:
False
In [3]:
bool(-0.5)

Out[3]:
True
In [4]:
bool("Engsci is the best")

Out[4]:
True
In [5]:
bool("False") #Not the empty string!

Out[5]:
True

We can also convert bools to integers:

In [6]:
int(True)

Out[6]:
1
In [7]:
int(False)

Out[7]:
0

This suggests a neat trick for the "ice cream or pie" issue:

In [8]:
pie = True
ice_cream = False
if int(pie)+int(ice_cream) == 1:
print("I didn't lie")

I didn't lie


## A bit about Boolean algebra (optional)¶

We can draw a (somewhat) loose analogy: if 0 is False and 1 (or anything positive) is True, then and roughly corresponds to * and or roughly corresponds to +

1 * 1 == 1       True and True  == True
1 * 0 == 0       True and False == False
1 + 0 == 1       True or  False == True



In this case, not A would corresond to (1-A)

### Why worry about converting strings and bools?¶

Here's an example of a common bug:

In [9]:
a = "abc"
if a:
print("hi")

hi


This doesn't produce an error, since a (not being "") gets converted to True. In this case, the programmer might have meant something like if a == "aaa".