Remember that question we had in the previous section: “Is the amount we want to withdraw from a bank account greater than the account balance?” It turns out we have to also make sure that the customer isn’t trying to take out a negative amount. The question we really need to ask is: “Is the amount we want to withdraw from a bank account less than zero or is it greater than the account balance?” If either one of those things happens, we can’t let the customer do the transaction.
Try again. Each comparison must be between exactly two values. In this case the right-hand expression < 5 lacks a value on its left.
x > 0 or x < 5
Try again. Although this is legal Python syntax, the expression is incorrect. It will evaluate to true for all numbers that are either greater than 0 or less than 5. Because all numbers are either greater than 0 or less than 5, this expression will always be True.
x > 0 and x < 5
Correct! With an and keyword both expressions must be true so the number must be greater than 0 an less than 5 for this expression to be true. Although most other programming languages do not allow this mathematical syntax, in Python, you could also write 0 < x < 5.
Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as “true.”
This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it until you are sure you know what you are doing.