What is passed back to the caller?
-Nothing!
What is displayed?
-The values at those memory address(es) are displayed on the screen.
input method
var = input("value returned from this function is always a string")
docstring
Built-in function help() displays the docstring from a function definition
Function Design Recipe
1. 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"?
2. Type Contract
What are the parameter types?
What type of value is returned?
3. Header
Pick meaningful parameter names.
4. Description
Mention every parameter in your description.
Describe the return value.
5. Body
Write the body of your function.
6. Test
Run the examples.
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
Function Reuse
Function calls
week3
Functions, Variables, and the Call Stack, frames, namespace
len(list): return the length of list.
min(list): return the smallest element in list.
max(list): return the largest element in list.
sum(list): return the sum of elements of list (where list items must be numeric).
list methods
help(list)
Lists elements may be of any type
Mutability
mutable: they can be modified
list, dict, set
immutable: they cannot be modified
str, int, float and bool, tuple, frozen set
Aliasing
A side affect. Hard to find bugs
RANGE
range([start,] stop[, step]):
return a virtual sequence of numbers from start to stop by step
week 6
FOR loops over indices
# Iterating over the indices of a list
for i in range(len(lst)):
print(lst[i])
Parallel Lists and Strings
Corresponding Elements
Nested Lists
Lists can contain items of any type, including other lists
Nested Loops
The bodies of loops can contain any statements, including other loops.
Reading Files
open(filename, mode)
'r' - to open for reading
'w' - to open for writing
'a' - open for appending to what is already in the file
File read methods
readline()
When you want to process only part of a file.
for line in file
process every line in the file one at a time
readlines()
return all lines in a file in a list
read()
read the whole file at once and use it as a single string