Wednesday 25 May 2011

Comparison and Boolean Operators

In this next lesson we will discuss Comparison operators and Boolean operators.

Comparison Operators are used to compare the values of two objects.
Boolean Operators allow us to combine comparisons.



Operator Description
 ==

is equal to
!= is not equal to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

Using the above operators we are able to make decisions based on the outcome of the comparison.

Example
>>> a = 5
>>> b = 2
>>> a < b
False

The result of the comparison will either be True or False, depending on the values being compared.

Boolean Operators (and, or, not) are used to combine comparisons. These can be used when either one, both, or two or more conditions need to be met.

Example
IF (today is monday and payday is monday) THEN
        cash check

The above example will only return a result if both the current day is Monday, and the payday variable is Monday.

Example
IF (x >= 0 and x <= 5) THEN
     PRINT x is between 0 and 5 (inclusive)

IF (x <= 2 or x >= 4) THEN
    PRINT x is less than or equal to 2, or greater than or equal to 4

not a == b and c == d


The first example will only execute if x is both greater than or equal to 0 and less than or equal to 5. Meaning that x must be either the value 0, 1, 2, 3, 4 or 5.

The second example will execute if either x is equal to or less than 2 or if x is greater than or equal to 4. This means that if x is any value except 3, it will execute as the value 3 is neither <= 2 or >= 4.

The third example uses the not operator which negates the value of the operand, converting True to False and False to True. This means that if a is not equal to b and c is equal to d then it will return True. A more expanded example is shown below:

>>> a = 5
>>> b = 3
>>> c = 6
>>> d = 6
>>> a == b
False
>>> c == d
True
>>> not a == b
True
>>> not c == d
False
>>> not a == b and c == d
True

As you can see from above:
a and b are not equal, thus when compared it returns False.
c and d are equal, and thus when compared they return True.
using not a == b returns True when compared because it is evaluating it as: a is not equal to b, which is true.
Hence when using not a == b and c == d, the return is True because a is not equal to be and c is equal to d.

This can be a bit hard to get a grasp of at first, and if you need to, play around with variables and values and see how it works when you use the not operator. You will get the hang of it soon.

Once you have completed this section, move on to the next: Selection Structures

-Nathan (everythingPython)

1 comment:

  1. , I read this blog please update more content on python, further check it once at python online training

    ReplyDelete