Labs‎ > ‎

Week02

Checklist Due Tuesday September 3rd at 11:59pm in your Portfolio.

  1. Do all the exercises at the end of Chapter 2 of HTLCS:
  2. Do all the exercises at the end of Chapter 3 of HTLCS:
  3. Write the unit conversion programs below under "Converting Units"
  4. Write your inches to centimeters and centimeters to inches programs using functions.

Converting Units

  • Consider the following Python program called feet_to_yards.py
$ cat feet_to_yards.py 
feet = input('Enter feet: ')
yards = feet / 3.0
print 'Yards:', yards

$ python feet_to_yards.py 
Enter feet: 21
Yards: 7.0

  • Write a similar program that converts inches to centimeters, call it inches_to_centimeters.py
  • Write a similar program that converts centimeters to inches, call it centimeters_to_inches.py

Functions for Converting Units

  • In the program above we requested input and directly computed the unit conversion.
  • We may want to perform unit conversion more than once
  • For this, we can write a function.
  • A function takes input (as a list of arguments) and gives output (as a single result)
  • For example:
$ cat feet_to_yards_func.py 
def feet_to_yards(feet):
    yards = feet / 3.0
    return yards

feet = input('Enter feet: ')
yards = feet_to_yards(feet)
print 'Yards:', yards

  • We use the Python def statement to "define" a function.
  • You provide the parameters to the function within parenthesis ().
  • You need to include a colon ":" after the last, right paren.
  • You provide a function body on the following lines
    • These line must be indented by a consistent number of spaces
    • Typically we use four spaces
  • To return a value you use the return statement followed by a variable or value as an argument.
  • A function is a form of abstraction.  Abstraction is a key concept in computer science.
  • Now that we have a function, we can use it again, and again, and again.
  • As you can see this will save us a lot typing:
$ cat feet_to_yards_func_many.py 
def feet_to_yards(feet):
    yards = feet / 3.0
    return yards

feet = input('Enter feet: ')
yards = feet_to_yards(feet)
print 'Yards:', yards

feet = input('Enter feet: ')
yards = feet_to_yards(feet)
print 'Yards:', yards

feet = input('Enter feet: ')
yards = feet_to_yards(feet)
print 'Yards:', yards
air:week2 benson$ python feet_to_yards_func_many.py 
Enter feet: 39
Yards: 13.0
Enter feet: 100
Yards: 33.3333333333
Enter feet: 150
Yards: 50.0

Comments