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.
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part 2 – Modules and Functions, Strings
- Starting up with Python – Part 3 – Sequences and List, Slicing and Editing
- Starting up with Python – Part 4 – More list functions and Slicing lists
- Starting up with Python – Part 5 – Methods
- Starting up with Python – Part 6 – Sort and Tuples, Strings and stuff, methods and Dictionary
- Starting up with Python – Part 7 – If statement, Else and elif statements
- Starting up with Python – Part 8 – Nesting and Comparison operators
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.