1 / 6

Decisions

Learn about the boolean operators in Python - and, or, not. Understand how they operate on Boolean values and combine them to produce a new Boolean value. Discover their priorities and common mistakes to avoid.

bartona
Download Presentation

Decisions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Decisions Bool operators and, or, not

  2. 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.

  3. Truth Tables

  4. 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)

  5. 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

  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

More Related