Decision structures

In class exercises
The compute average program solution has been posted to update21. Run update21 at the command prompt to get these updates
$ update21
Creating /home/adas/cs21/inclass/w03-decisions
  Adding /home/adas/cs21/inclass/w03-decisions/speeding.py
  Adding /home/adas/cs21/inclass/w03-decisions/isOdd.py
  Adding /home/adas/cs21/inclass/w03-decisions/isAlpha.py
String Formatting
Until now, our only option for printing multiple data types in a single line was to use the comma.
myInt = 86
myFloat = 1./3
print "The value", myInt, "is an integer but ", myFloat, "is not"
We can get more control over how data values are displayed using string formatting. See Section 4.5.2 on page 102 for more examples.
myInt = 86
myFloat = 1./3
print "The value %d is an integer but %0.2f is not" % (myInt, myFloat)
Using this new style requires a few steps. First, set up a string that contains one or more formatting tags. All tags have the form %<width><.><precision><type-char>. The type-char is s for strings, d for integers (don't ask why), and f for floats. Do not put any variable names in the format string, just tags which serve as placeholders for data that will come later. After the format string put a single % symbol after the close quote. Finally, place the data elements that you wish to substitute for the tags separated by commas and enclosed in parentheses. Let's step through a few examples in the python shell.
>>> month="Sep"
>>> day=17
>>> year=2012
>>> print "Today is %d %s %d" % (day, month, year)
Today is 17 Sep 2012
>>> print "Tomorrow is %d/%d/%d" %(9,day+1, year)
Tomorrow is 9/18/2012
>>> for val in range(1,200,20):
...   print "%7.2f" % (val*6.582118)
... 
   6.58
 138.22
 269.87
 401.51
 533.15
 664.79
 796.44
 928.08
1059.72
1191.36
Number and letter representation
By now we know that python can save and store data in variable for future use. Additionally, vim and linux save our python programs in files for future use. Where does all this data go and how does the computer keep track of it all? For a full explanation, you would need to take one or more additional CS courses (Computer Organization or Operating Systems), but the short answer is that data is stored in the computers memory, which to an extremely rough approximation is like a sheet of graph paper where each cell can hold a single symbol. While we commonly work with the decimal digits 0-9, the letters a-z, and a few other common symbols, the computer really only understands two symbols: 0 and 1. These symbols can be represented as an electrical signal or bit that is either on (a 1) or off (a 0). Switches are easy to make, we can make them really small, and we can cram about half a billion of them into a single chip. A billion bits can store a lot of data, but it is still a finite resource. To represent data types such as integers, floating point numbers, and characters, we must encode these data types as a sequence of 1's and 0's. Integers are stored in binary format. Characters are stored using ASCII character codes. We can convert between characters and their ASCII equivalent using the functions ord and chr. A quick example is shown below. We will see how this is useful later.
>>> let='a'
>>> let
'a'
>>> ord(let)
97
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> chr(ord('d')+18)
'v'
>>> chr(ord('z')+2)
'|'
A word of caution: Do NOT use ASCII character codes directly. There is no need to memorize them in python. You may want to memorize them for party tricks, but it is unlikely that you will gain many friends this way. If you need to know the ASCII character of 'c', use ord('c'), not 99. If I see a spurious 65, 90, 97, or 122 in your code, I will take off points. I assign no significance to these numbers aside from the fact that 65 is the number of teams in the Men's NCAA basketball tournament, which is not very useful in python.
Decision structures
We'll be looking at some in class examples for decision structures today that will require you to copy some files from my directory.

Change into your inclass directory.

[~]$ cd
[~]$ cd cs21/inclass/
[inclass]$ ls
w01-intro/  w03-decisions/
If the w03-decisions directory does not yet exist, create it using update21
if, else, elif
Sometimes we need to make decisions based on various input parameters or conditions in our programs. Python supports automated decision making using if, else, elif syntax.
if <condition>:
  <body>


if <condition>:
  <body>
else:
  <body>
  
if <condition>:
  <body>
elif <condition>:
  <body>
else:
  <body>
The condition must be an expression that evaluations to true or false. The term Boolean is used to describe a type of data that can be either true or false.
temp=input("Enter the current temperature in Fahrenheit: ")
if temp <= 0: 
  print "%d is cold. Brrr!" % (temp)
else:
  print "%d is at least above 0" % (temp)
Boolean operators: <, >, <=, >=, ==, !=, and, or, not Why is == a Boolean operator instead of just =? Think syntax and semantics.
Never odd or even?
The first program we will look at is isOdd.py. Modify the program so that it prints out if a number entered by a user is odd or even. Think about how the mod or remainder operator % can be used with an if statement to solve this problem. Some sample runs are shown below.
$ python isOdd.py 
Please enter a number: 0
0 is even

$ python isOdd.py 
Please enter a number: 1243678
1243678 is even

$ python isOdd.py 
Please enter a number: 2371
2371 is odd
What did you type?
Next open isAlpha.py and modify the program so that it determines if a single character (a length 1 string) entered by the user is an uppercase letter, a lowercase letter, a decimal digit, or none of the above (usually punctuation). This program relies on python's ability to compare two strings using the operators < >, ==, <=, >=, and !=. Try it! Comparisons are done using the ASCII character codes. If you want to quickly see what happens, try a few example in a separate python shell. Some example runs of a sample program are shown below.
$ python isAlpha.py 
Enter a single keyboard character: 3
'3' is a decimal digit

$ python isAlpha.py 
Enter a single keyboard character: a
'a' is a lowercase letter

$ python isAlpha.py 
Enter a single keyboard character: Q
'Q' is an uppercase letter
What if the user enters more than one character? Can you inform them politely on how to run the program correctly?