The Six Steps
- Examples
- What should your function do?
- Type a couple of example calls.
- Pick a name (often a verb or verb phrase): What is a short answer to "What does your function do"?
- Type Contract
- What are the parameter types?
- What type of value is returned?
- Header
- Pick meaningful parameter names.
- Description
- Mention every parameter in your description.
- Describe the return value.
- Body
- Write the body of your function.
- Test
- Run the examples.
Applying the Design Recipe
The problem:
The United States measures temperature in Fahrenheit and Canada measures it in Celsius. When travelling between the two countries it helps to have a conversion function. Write a function that converts from Fahrenheit to Celsius.
- Examples
>>> convert_to_ccelsius(32) 0 >>> convert_to_celsius(212) 100
- Type Contract
(number) -> number
- Header
def convert_to_celsius(fahrenheit):
- Description
Return the number of Celsius degrees equivalent to fahrenheit degrees.
- Body
return (fahrenheit - 32) * 5 / 9
- Test
Run the examples.
Putting it all together:
def convert_to_celsius(fahrenheit): ''' (number) -> number Return the number of Celsius degrees equivalent to fahrenheit degrees. >>> convert_to_ccelsius(32) 0 >>> convert_to_celsius(212) 100 ''' return (fahrenheit - 32) * 5 / 9