done
Chapter 3 Boolean Logic
We will start leaning simple basic logic that makes real programs work. Try to remember these concepts, it's very important skill a programmer will need.
3.1 Boolean
So far we've learned that integer, floating-point and string data types have unlimited number of possible values, the Boolean data type has only two values: True and False.They are used to represent truth values (although other values can also be considered false or true)
- True, False are capitalized, no quotes like around strings.
- Don't use True/False as variable names.
Ex. 3.1-1 Boolean_value
>>>p=True
>>>q=False
>>>p
True
>>>q
False
>>> bool(p)
True # see below for bool( )
>>>
The built-in function bool()
can be used to cast any value to a Boolean, if the value can be interpreted as a truth value.
Ex. 3.1-2 use bool()
>>>bool(2==3)
False
>>>bool('hi'=='Hi')
False
>>>bool(2*4==2**3)
True
>>>
3.2 Operators
We can produce Booleans without assigning them to variables, but instead make comparisons and evaluations using operators. We can work with the following:
Comparison operators compare two values and return True
or False
:
Ex. 3.2-1 comparison
# ex. 3.2-1
>>> 25 == 5*5 # equal to, ==
True
>>> 25 != 25 # Not equal to, !=
False
>>> 25 > 5**2 # Greater than, >
False
>>> 25 >= 5**2 # Greater than or equal to, >=
True
>>> 25 <= 5*5 # Less than or equal to, <=
True
>>> 'hi' == 'Hi' # stings are case sensitive
False
>>> 'Cat' != 'Chicken'
True
>>>peanut, watermelon = 10,1 #assign values to variables
>>>peanut < watermelon
False
>>>
# == and != can work with any data type,
# >, >=, <, <= can only work with numbers
Boolean operators ( and, or, not) are used to compare Boolean values.
The Truth Tables:
and: if both are
True
, the result isTrue
True and True------ True True and False----- False False and True----- False False and False----- False
or:
True
if either of the two Boolean values isTrue
.True or False ----- True False or False----- False
not: operates on only one Boolean value (or expression). Result is the opposite.
not True----- False not False --- True
Ex. 3.2-2 Boolean
operators
# ex. 3.1-2
>>>False and True
False
>>>4==2*2 and 2==3 # True and False
False
>>>(5<10) or ( 10>= 5*2) # True or True
True
>>> 'Hi, there!' != 'HI' or 4==8 # True or False
True
>>> 'Cat'=='Dog' and not (6==8 or 3==3)
False
# F and not(F or T), this is F and F--> F
Tricks for quick evaluation:
- Solve what's inside parentheses first
- Find each not and invert it
- Replace an == or != with its result
- At the end you should have True or False
Steps to solve, evaluate this:
not('Hello'!='hello' or 'Buzz'=='Buzz') and 2!=4
- in parentheses, (T or T) is T
- 2!=4 is T
not
(T or T)and
T is Fand
T, so the result is False
While these are all interesting and puzzling, what't the point to keep comparing cats and dogs, let's move on to next chapter, Making Decisions!