60 likes | 321 Views
Decisions. Bool operators and, or, not. Boolean operators. In Python, not, and and or are Boolean or logical operators Note that is NOT the same as the relational operators Boolean operators operate ONLY on Bool values and produce Bool values
E N D
Decisions Bool operators and, or, not
Boolean operators • In Python, not, and andor are Boolean or logical operators • Note that is NOT the same as the relational operators • Boolean operators operate ONLY on Bool values and produce Bool values • andandor are used to combine two Bools into one • not is a unary operator, it reverses a Bool to the opposite value • Their priority is lower than the relational operators • Their individual priorities are not followed by and followed by or. • The truth tables on the next slide show how they operate, their semantics.
Examples • Given that x is 5, y is 9.2, z is 0 • x + 5 > y * 3 and y > z works out as x + 5 > 27.6 and y > z (* done first) 10 > 27.6 and y > z (+ done next) False and y > z (relationals done left to right) False and True (second relational done) False (result of and)
Cautions • In most languages the expression 5 < y < 10 does not mean what you would think. In Python it does – it is True if y is between 5 and 10. It is the same as saying 5 < y and y < 10 • The expression x == 5 or 6 does NOT mean what you would think. In fact it is considered always True in Python. Why? 6 after the or operator is considered a separate value – it is NOT compared to the x. The or operator needs a Bool value there, so it forces (“coerces”) the 6 value to be True (anything not zero is True). And from the truth table for or, you can see that anything or True is True! To have the interpreter see it correctly, you write it as x == 5 or x == 6
Always True or Always False • You can easily write expressions which are always True or always False. This is an error. The interpreter will not tell you about them. • Always True: x > 5 or x < 8 • Always False: y > 10 and y < 0 • Always True: y != 10 or y != 5