3.7.2 Comparison tests and Booleans

The [condition] is generally written in the same way as in maths. The possibilites are shown below:

Comparison  What it tests 
a < b a is less than b
a <= b a is less than or equal to b
a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a < b < c a is less than b, which is less than c

The == is not a mistake. One = is used for assignment, which is different to testing for equality, so a different symbol is used. Python will complain if you mix them up (for example by doing if a = 4).

It will often be the case that you want to execute a block of code if two or more conditions are simultaneously fulfilled. In some cases this is possible using the expression you should be familiar with from algebra: a < b < c. This tests whether a is less than b and b is also less than c.

Sometimes you will want to do a more complex comparison. This is done using boolean operators such as and and or:

      if x == 10 and y > z:
          print "Some statements which only get executed if"
          print "x is equal to 10 AND y is greater than z."
      if x == 10 or y > z:
          print "Some statements which get executed if either 
          print "x is equal to 10 OR y is greater than z"

These comparisons can apply to strings too3.9. The most common way you might use string comparions is to ask a user a yes/no question3.10:

      answer = raw_input("Evaluate again? ")

      if answer == "y" or answer == "Y" or answer == "yes":
          # Do some more stuff

EXERCISE 3.7
Write a program to ask for the distance travelled and time take for a journey. If they went faster than some suitably dangerous speed, warn them to go slower next time.



Footnotes

... too3.9
although something like mystring > "hello"is not generally a meaningful thing to do.
... question3.10
Note string comparisons are case sensitive so "y" != "Y".