COSC 235: Programming and Problem Solving
March 18, 2009

Joseph D. Sloan
sloanjd @ wofford.edu


Decision Structures

Using if, elif, and else

if and elif contain test.
Multiple elif are allowed
elif and else are optional
Note the use of : and indentation.

if (bmi < 25):
   print "Keep up the good work."
elif (bmi < 35):
   print "You could stand to lose a few pounds."
else:
   print "I think we have a serious problem here."   

Relational Operators: <, <=, >, >=, !=, ==
Compound expressions with: and, or, not
Evaluate to: True, False

Example from text on Max of three numbers
Pay attention to when to use > vs. >=

Misc Idioms & Issues with Decisions

Note x = 1 and x == 1 are different

Unlike most languages, constructs like 1 < x < 5 are allowed in Python.

Exclusive or vs. inclusive or: English language use or is an exclusive sense—one, the other but not both. In programming, or is used inclusively—one, the other, or both.

Even idiom: x % 2 == 0
Odd idiom: x % 2 == 1 or x % 2 != 0

Decision Tree

One level for each elimination

Problems comparing floating point numbers

Example

x = 1.0/10.0
sum = 0
for i in range(10): sum += x
sum == 1.0
print x, sum

Alternatives: stict to integers or range testing

abs(sum - 1.0) < 0.0000005
-0.0000005 < sum - 1.0 < 0.0000005

User input testing

Required for most code projects
Make sure values are reasonable, eg., height in feet is between 3 feet and 8 feet.

Homework

Friday:

Attached

Energy density calculator: The energy density of a food is the number of calories in a serving divided by the number of grams in a serving. For example, if a serving is 40 grams and has 150 calories, then the energy density is 3.75, (i.e., floating point division with 150 divided by 40). If you are trying to lose weight, you should eat foods with lower energy densities. Conversely, if you want to gain weight, then you should eat foods with higher energy densities. Write code to calculate energy densities using a GUI interface. Use the Celsius Converter in Section 5.7.2 as a model. ßß

Monday:

P 226: MC

Code decision tree from Friday's homework.

Wednesday:

Add comments to your Energy Density calculator as described below. You should also check input values to insure that they are reasonable. Be sure to correct any existing problems as well including documentation. Submit the code as an email attachment.

Assuming you are trying to lose weight:
If ED is between 0 and 0.6, it is very low and you can eat the food without restraint;
If ED is between 0.6 and 1.5, it is low and you can eat with minor restraints;
If ED is between 1.5 and 4.0, it is medium and you should watch portions;
If ED is between 4.0 and 9.0, it is high and you should closely limit or avoid the food.
Alter your GUI so that it prints appropriate comments based on this information.


This page was created by Joe Sloan.
It was last modified around: 20 March 2009
Send mail to: sloanjd@wofford.edu

ß