COP 3223H meeting -*- Outline -*- * Boolean expressions ** Boolean values ------------------------------------------ BOOLEAN VALUES IN PYTHON The two values: are the only values of type bool ------------------------------------------ ... False, True Note the initial capital letters, show what happens when you give true or false to the interpreter! ** Boolean Expressions *** Boolean operators ------------------------------------------ OPERATORS ON BOOLEANS >>> True and True >>> True and False >>> False and True >>> False and False >>> True or True >>> True or False >>> False or True >>> False or False >>> not True >>> not False ------------------------------------------ Q: So what does "and" do? it tells if both subexpressions are True. This is && in C Q: What does "or" do? it tells whether one subexpression is True This is || in C Q: What does "not" do? it changes True to False and vice versa, negating the expression. This is ! in C *** Boolean-valued expressions You rarely need to write True or False explicitly in a program, because most boolean values arise from other expressions... ------------------------------------------ BOOLEAN-VALUED EXPRESSIONS Comparisons have bool values: >>> 2 < 3 >>> 2 < 3 >>> 3 > 2 >>> 2 > 3 >>> 2 == 2 >>> 2 == 3 >>> 2 = 2 # error! >>> v = 2 >>> v = v # what does this do? >>> v == v >>> 2 != 3 >>> not (2 == 3) >>> 2 <= 3 >>> 2 < 3 or 2 == 3 >>> 3 <= 2 >>> 3 <= 3 >>> 2 <= 2 >>> 2 <= 3 and 3 <= 4 ------------------------------------------ Note the difference between == and = in Python Q: What does <= mean? Q: How is <= different from < in expressions? Q: What do you think the >= operator does? Actually 2 <= 3 and 3 <= 4 can be written 2 <= 3 <= 4 in Python, but not in most other languages (like C). ** Tips for writing Boolean expressions ------------------------------------------ DON'T USE TRUE AND FALSE EXPLICITLY Rule 1 Prefer: instead of e == True Example: if weight <= 160 and height <= 6: return "OK" vs. if (weight <= 160 and height <= 6) == True: return "OK" ------------------------------------------ ... e ------------------------------------------ DON'T USE TRUE AND FALSE EXPLICITLY Rule 2: Prefer: instead of: e == False Example: if not (weight <= 160 and height <= 6): return "Heavy" vs. if (weight <= 160 and height <= 6) == False: return "Heavy" ------------------------------------------ ... not e