Comparisons and boolean operators
Resources
- Official documentation on comparisons, and boolean operators.
- Real python tutorial on boolean operators.
Comparisons
A critical part of any programming language is the comparison between items. For instance, is a number equal to the result of an operation? Is is bigger or maybe smaller? Some of the operators used are:
- equal (==),
- less than (<),
- less or equal (<=),
- greater than (>),
- greater or equal (>=),
- not equal (!=).
Assignment and equality
It is very important to understand the difference between the assingment operator (=) and the comparison operator (==). The assigment operator is used to assign a value (an object) to a variable, whereas the comparison operator is used to find out if two objects are the same or not.
Remember that the comparison operator is ==, not =.
name1 = “John” name2 = “John” print(a == b)
There is a catch with the floats. It is OK to check if they are greater or lower, but do not use the equality operator (==) to check if they are the same because the comparison might fail. Remember that floats are approximate. If you want to check if two floats are very similar you have to use the isclose function. This function is not directly avilable, you have to import it from the math module, we will work with modules in the future.
Use the comparison operator for the integers and the isclose function for the floats.
None is None
None represents another special case. You might check if a variable is None using the equality operator, but is it recommended to use the is operator.
Operations with booleans
The boolean type has special operators: and, or, not. These operators define a boolean arithmetic.
Explore the boolean arithmetic which are the results for all the combinations of and and or.
Try all True and False combinations with and and or.