Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

some tricks you can use to combine more than one condition check into a single if statement.


Using Logic Operators


Python allows you to use the logic operators (see Hour 5, “Using Arithmetic in Your Programs”) to
group comparisons together. Since each individual condition check produces a Boolean result value,
Python applies the logic operation to the condition results. The result of the logic operation
determines the result of the if statement:


Click here to view code image


>>> a = 1
>>> b = 2
>>> if (a == 1) and (b == 2): print("Both conditions passed")

Both conditions passed
>>> if (a == 1) and (b == 1): print("Both conditions passed")

>>>

When you use the and logic operator, both of the conditions must return a True value for Python to
process the “then” statement. If either one fails, Python skips the “then” code block.


You can also use the or logical operator to compound condition checks:


Click here to view code image


>>> if (a == 1) or (b == 1): print("At least one condition passed")

At least one condition passed
>>>

In this situation, if either condition passes, Python processes the “then” statement.


Combining Condition Checks


You can combine condition checks into a single condition check without using logic operators. Take a
look at this example:


Click here to view code image


>>> c = 3
>>> if a < b < c: print("they all passed")
they all passed
>>> if a < b > c: print("they all passed")
>>>

In this example, Python first checks whether the a variable value is less than the b variable value.
Then it checks whether the b variable value is less than the c variable value. If both of those
conditions pass, Python runs the statement. If either condition fails, Python skips the statement.


Negating a Condition Check


There’s one final if statement trick that Python programmers like to use. Sometimes when you’re
writing if-else statements, it comes in handy to reverse the order of the “then” and “else” code blocks.


This can be because one of the code blocks is longer than the other, so you want to list the shorter one

Free download pdf