11. Conditional Evaluation

11.1. Basic Theory

All computer languages allow comparison of the contents of variables with the contents of other variables (or with numbers, strings...). Tests are

  • < less than

    <= equal or less than

    Note
    In the spirit of completely gratuitous changes, python doesn't accept =< used in other languages, but does accept <= (which is reasonable, it's how you say it verbally). Just watch for the syntax error messages (you can't let your life be dominated by other people's idiocyncracies). It would be reasonable in a new language like python, to allow both <= and =<.
  • > greater than

    >= greater than or equal

  • == equal

    != not equal

Following the test, code execution can branch in various ways e.g. (here shown in pseudo code)

  • if (temperature > 80 degrees)
    then
    	turn on airconditioner
    endif
    

    There is one branch of the conditional, which turns on the airconditioner. If the temperature is less than 80°, then the program continues execution without turning on the airconditioner.

    What does the code immediately above do at 79° [55] ?

  • if (temperature > 80 degrees)
    then
    	turn on airconditioner
    else if (temperature =< 60 degrees)
    	turn on the heater
    endif
    

    There are two branches of the conditional. If the temperature is more than 80° or less than or equal to 60°, then the program branches, otherwise execution continues without branching.

    What does the code immediately above do at 60° [56] ?

  • if (temperature > 80 degrees)
    then
    	turn on airconditioner
    else if (temperature < 60 degrees)
    	turn on the heater
    else
    	open the windows
    endif
    

    The conditional has three branches and does something different for temperatures below 60°, 60-80° and greater than 80°.

    What does the code immediately above do at 80° [57] ?

Note: python doesn't have this problem:

Here is a common coding bug. The comparison operators are unique to comparisons, but the "==" and "=" operators are similar, at least visually.

x=0 means "assign x the value 0"

x==0 means "test if x has the value 0"

In a conditional you want

if (x==0)
	do something
else
	do something else

If instead you do

if (x=0)
	do something
else
	do something else

then x will be assigned the value 0. The language must know whether a command succeeded (allowing execution to continue, or to bail out with an error) and since assigning x=0 will always succeed, then execution will branch to the "do something" branch, independant of the original value of x.

Since you're unlikely to ever want to execute the instruction

if (x=0)

the language should trap this construct as a syntax error. None of them do, at least till python came along. This is why rockets continue to blow up, cars have different bumper heights and we had lead in paint for so long.

Here's the official Python Tutorial, section 4.1 If Statements (http://docs.python.org/tut/node6.html#SECTION006100000000000000000)

Note
I live in one of the few (the only?) country that uses Fahrenheit, miles, lbs... (and the country's currency is loosing value, while the economy is only surviving by exporting jobs to our competitors.) If you live in the rest of the world, please substitute other values in these examples. I also live in a part of the world where you need an airconditioner in the summer and heater in winter (I lived quite happily in another part of the world for the first 30yrs of my life without these things and had some trouble adjusting to living indoors). I still wonder why people settled in such places when they didn't have to.

11.2. Temperature Controller, air conditioner only

Here's the python syntax for a single branching conditional statement.

if x < 0:
	print 'Negative number found'

fire up your editor to code up the file temperature_controller.py

  • declare a variable temp giving it a value of 85.
  • if temp>80, print a message saying "the temperature is" and giving the temperature followed by a period. Then on the same line, output "Am turning on the air conditioner.". Use blanks and spacing to make the output human readable.
  • save your program and run it. Once it runs, change the value of temp to 75 and rerun the program, to check that it runs correctly.

Here's my code [58] .

11.3. Temperature Controller, air conditioner v2

Here's python code for a two branch conditional.

if x < 0:
       print "Negative number found"
    else:
       print "non negative number found"

starting with your current temperature_controller.py, add code to output the string "no action taken" if the temperature is 80 or below. Check your code with values of temp above and below 80°.

Here's my code [59] .

11.4. Temperature Controller, air conditioner and heater

Here's another python conditional construct

if x < 0:
      print 'Negative number found'
elif x == 0:
      print 'Zero'
else:
      print 'Positive number found'

Use this construct to add a branch to temperature_controller.py which turns on the heater at 60° or below and outputs a message describing its action.

Here's my code [60] .

11.5. Temperature Controller, air conditioner, heater and window opener

Change the preceding code to open the windows if the temperature is 61-80°. Test your code to confirm that all branches execute at the expected temperatures. Here's my code. [61] .

11.6. Temperature Controller, formatting output

In our current version of temperature_controller.py, the string "the temperature is " is in all branches, so will be output no matter what. In this case the string could be output once, below the declaration of temp. Here's a print statement using a trailing ',' that doesn't put a carriage return at the end of the output line.

name = "Homer"
print "my name is", name,

Use this code fragment to only have one copy of the string "the temperature is" in the code. Here's my version [62] .

Note that you can't get the period correctly spaced after the temperature. Python thinks it knows what you want better than you do and outputs a gratuituous blank that you didn't ask it to output.

Formatted output allows you more control over your print statements. Use this code fragment to produce a better output for temperature_controller.py (the %d says to put the decimal value of the argument in that place in the string).

>>> temp = 65
>>> print "the temperature is %d." % temp
the temperature is 65.

Here's the improved code [63] . Note that python still outputs a gratuituous blank when it executes the comma.

Note
End Lesson 8