Week 2
Week 2
If a string begins with a single quote, it must end with a single quote. The same
applies to double-quoted strings. You can not mix the type of quotes.
Escape Sequences
To include a quote within a string, use an escape character (\) before it. Otherwise
Python interprets that quote as the end of a string and an error occurs. For example,
the following code results in an error because Python does not expect anything to
come after the second quote:
>>> storm_greeting = 'wow, you're dripping wet.'
SyntaxError: invalid syntax
The escape sequence \' indicates that the second quote is simply a quote, not the
end of the string:
>>> storm_greeting = 'Wow, you\'re dripping wet.'
"Wow, you're dripping wet."
String Operators
The * and + operands obey by the standard precedence rules when used with
strings.
Lecture 2(Optional)
1. Examples
o What should your function do?
o Type a couple of example calls.
o Pick a name (often a verb or verb phrase): What is a short answer to
"What does your function do"?
2. Type Contract
o What are the parameter types?
o What type of value is returned?
3. Header
o Pick meaningful parameter names.
4. Description
o Mention every parameter in your description.
o Describe the return value.
5. Body
o Write the body of your function.
6. Test
o Run the examples.
The problem:
1. Examples
2. >>> convert_to_ccelsius(32)
3. 0
4. >>> convert_to_celsius(212)
5. 100
6.
7. Type Contract
8. (number) -> number
9.
10.Header
11. def convert_to_celsius(fahrenheit):
12.
13.Description
14. Return the number of Celsius degrees equivalent to fahrenheit
degrees.
15.
16.Body
17. return (fahrenheit - 32) * 5 / 9
18.
19.Test
20. Run the examples.
21.
>>> convert_to_ccelsius(32)
0
>>> convert_to_celsius(212)
100
'''
LECTURE 3
Function Reuse
Calling functions within other function definitions
>>> perimeter(3, 4, 5)
12
>>> perimeter(10.5, 6, 9.3)
25.8
'''
return side1 + side2 + side3
>>> semiperimeter(3, 4, 5)
6.0
>>> semiperimeter(10.5, 6, 9.3)
12.9
'''
return perimeter(side1, side2, side3) / 2
The problem: One triangle has a base of length 3.8 and a height of length 7.0. A
second triangle has a base of length 3.5 and a height of length 6.8. Calculate which
of two triangles' areas is biggest.
The approach: Pass calls to function area as arguments to built-in function max.
max(area(3.8, 7.0), area(3.5, 6.8))