Starting up with Python – Part9

Part 9 of this Python fiesta on TheTunnelix is going to be more fun. I will now focus on And and Or operators. Here is a recap where we have reached if you are not following the Python blog posts since the beginning.

Starting up with Python - Part9 1

Starting up with Python - Part9 2

20. And and Or operators

To check if 2 conditions are true, we can also use the conditions called 'And'. The code below will output the answer 'number1 is between 3 and 2o' Same could be achieved by using the if and else statement.

#! /usr/bin/env python
number1 = 5
if number1 > 3 and number1 < 10:
 print 'number1 is between 3 and 10'

However, we would also notice that in an And statement, if only one part of the statement is true, nothing would be printed. See example below where we would notice number1 < 4 which is fake. This would never print anything on the screen.

#! /usr/bin/env python
number1 = 5
if number1 > 3 and number1 < 4:
 print 'number1 is between 3 and 10'

In this case, we can use an Or operator to output what we really want. See example below 

#! /usr/bin/env python
number1 = 5
if number1 > 3 or number1 < 4:
 print 'this works fine'

As we have seen in the And statement if a part is not true it will not print anything on the screen compared to the Or statement either both are true just one part is true. If any part of the Or statement is false, it won't work.