COSC 235: Programming and Problem Solving
February 9, 2009

Joseph D. Sloan
sloanjd @ wofford.edu


Variations on the Chaos program: 20 times, prompt # of times, two column, labeled column
range()

Simple Programming

Difference between input() and raw_input() and t
The difference between strings and numbers.
Function names line main() in file.

Note the difference between strings and printing strings:

>>> test = "x\nx"
>>> test
'x\nx'
>>> print test
x
x

Input ==> Process ==> Output model for coding

Think about what is required to do a calculation and what is produced.
Think about how you would solve the problem manually, with pencil and paper.
Although it sounds like new-age clap-trap, "try to be the computer".

Difference Between print and return

Return allows results to be used in other calculations.

def bmi(h, w):
  return w / (h * h)

Print allows labeling and format control.

def bmi(h, w):
   print "The BMI is ", w / (h * h)

With care, both can be used.

Difference between print and return. return allows results to be used in other calculations. print allows labeling and formatting. Both can be used with care.

Nesting Functions with return

def usaBmi(f, i, w):
  return bmi(ftAndInToMeters(f,i), poundsToKilos(w))

Prompts and Interactive Code

def interactiveBmi():
  h = input("Height in meters: ")
  w = input("Weight in kilos: ")
  return bmi(h, w)

Be sure to use good promts when writing interactive code.

Note nesting of functions.

Homework

1. Write a function ftAndInToMeters() that takes a height in feet and inches and returns the height in meters. For example, ftAndInToMeters(5, 11) would return 1.8034, i.e., 71 inches converted to meters.

2. Write an interactive version of BMI that prompts the user to enter the height in feet and inches and the weight in pounds and prints the correct BMI. For example:

>>> interactBMI()
Enter height in feet and inches.
The number of feet is:
5
The number of inches is: 11
Enter the weight in pounds: 170
The BMI is ...

Turn in a printout of the code for each.

 


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