Class 42 — Monday, December 6
One more chance to be a class
Programming basics — Your semester achievement — Bask in the success
Dream big and work hard — Celebrate diversity — Always pay forward
Look both ways
Agenda
- Answer questions
Thanks again to the TAs for making the course successful
Amshala Bharathan Kevin Luk Sophia Rogers Meghan Tracy Katherine Brickley Rachel McNamara MaryJeanine Seaman Bailey Greggs Jimmy Njuguna Shivania Surtio
Want to be a TA for CS 1112
- Departmental application
Test 3
- Form to indicate your intention to take test
- The default is you are not taking Test 3. Students who want to take test 3 must indicate their intention before the end of class on Monday, December 6.
Past homework
- Solutions are available
Test taking
- Students are expected to take the test in Rice 130 on Friday.
What to expect for the test
- Use of if
input()
statement
- Knowledge of
if
,for
, andwhile
statements; along with the ability to use them when problem solving.
- Ability to write functions using and producing numbers, strings, lists, dictionaries, datasets, and random values.
- Simple image manipulation
Built-in functions
id( v )
: returns indicator where in memory to findv
.
type( v )
: returns the type of value stored inv
.
abs( v )
: returns absolute value ofv
.
len( s )
: returns number of things making ups
.
min( s )
: returns minimum value ins
.
max( s )
: returns maximum value ins
.
sum( s )
: returns the sum ofs
.
int( s )
: returns an integer constructed froms
.
float( s )
: returns a decimal constructed froms
.
string( v )
: returns a string constructed froms
.
sorted( s )
: returns a sorted version ofs
.
Functions
- Functions can be invoked.
- The invocation identifies the function to be started up.
- The invocation includes the arguments. The arguments are evaluated. Copies of the values are used to initialize the parameters specified in the function definition.
- Functions must be defined. A function definition consists of a header followed by its body.
- Header:
def name ( parameters ) :
- Body: remaining lines in function. How can you tell? They are indented. Body is also known as the statement list
- A
return
is a special statement in the body of function. When areturn
statement is reached in a function, the function stops executing its instructions; that is, the function immediately stop its execution.
- A
return
statement can optionally have a return expression following the keywordreturn
. The expression is evaluated. A copy of that value is the return value of the function. The return value is said to be the value of the evaluation of the function invocation.
- All Python functions return values – if no
return
statement with a return expression is executed. The function returnsNone
.
- A local variable is a variable initialized/defined inside a function definition.
- Local variables only exist inside the function definition (limited scope)
- The parameters of a function are the variables listed with the parentheses in the function header.
- Parameters are local variables
- The arguments to a function are the values given within the parentheses of an invocation of the function.
- The Python way of handling the arguments is pass by value; that is, the arguments are evaluated to determine their values. Copies of those values are used to initialize the parameters.
- Because Python uses pass by value, the value of an argument is unchanged by a function invocation; that is, the value of an argument is the same after the invocation as it was before the invocation.
- Implication: not possible to write a swapping function in Python
- Because a parameter has the same value as its argument, if that argument is a list, the contents of that list can be modified. Such a change is called a side effect of the function. Functions with side effects generally have a return value of None.
Sequence expression — adapted in part from docs.python.org
Operation | Evaluation |
len( s ) | Length of sequence s |
sum( s ) | Sums the items in sequence s |
min( s ) | Smallest item in sequence s |
max( s ) | Largest item in sequence s |
x in s | True if an item of sequence s equals x ; otherwise, False |
x not in s | False if an item of sequence s equals x ; otherwise, True |
s + t | New concatenation of sequences s and t |
s[ i ] | Value of item at index i th of sequence s |
s[ : ] | New copy of sequence s |
s[ i : ] | New copy of sequence s for the elements from index i up to and including last sequence element |
s[ : j ] | New copy of sequence s for the elements from index 0 up to but not including index j |
s[ i : j ] | New copy of sequence s for the elements from index i up to but not including index j |
s[ i : j : k ] | New copy of sequence s for the elements from index i up to but not including index j with step k |
s.index( x ) | Index of the first occurrence of item x in sequence s |
s.index( x, i ) | Index of the first occurrence of item x in sequence s at or after index i |
s.count( x ) | Total number of occurrences of item x in sequence s |
s * n | New sequence equivalent to adding sequence s to itself n times |
List patterns
- Suppose below
alist
,blist
, andclist
are lists and that valuev
is not a list
- To analyze a list use
result = ...
for element in alist :
...
return result
- To modify a list use
n = len( alist )
for i in range( 0, n ) :
element = alist[ i ]
...
alist[ i ] = element
- Important list operations
alist.append( v )
- Appends
v
to end ofalist
.
alist.remove( v )
- Removes first occurence of
v
fromalist
.
alist.index( v )
- Index of first occurrence of
v
inalist
.
clist = alist + blist
- Concatenates
alist
andblist
to makeclist
.
v = alist.pop( )
- Removes the last element from
alist
. The value of that former element is the return value assigned tov
.
v = alist.pop( i )
- Removes the element at index
i
fromalist
. The value of that former element is the return value assigned tov
.
- List gotchas
blist = alist + v # cannot add a list and a non-list
alist = alist.append( v ) # alist is no longer a list, it is None
Warnings
- A
print()
statement in a function is not supplying a return value. It is sending a message to the program user.
- An
input()
statement is wrong to include in a function body, information comes into a function through its parameters.
- No function you will be asked to implement should have a
print()
orinput()
statement.
FWIW
- Nested for-loops usually wrong unless using a list-of-lists (e.g., a dataset) or looking at one list in relation to another list or image manipulation
Dictionaries
- Unordered collection of key-value pairs
- Initialization examples
d = { 18 : "voting", 67 : "retirement", "CS 1112" : "course" }
d = {}
d[ 18 ] = "voting"
d[ 67 ] = "retirement"
d[ "eighteen" ] = 18
- Access values by key:
d[ 18 ]
- Means the same thing as "voting"
- Access values by key:
d[ 21 ]
- Will be an error because 21 is not a key
- Access values by key:
d[ "voting" ]
- Will be an error because
"voting"
is not a key
- Access values by key:
d.get( 18 )
- Means the same thing as
"voting"
- Access values by key:
d.get( 21 )
- Means the same thing as None (not an error)
- Access key by its value: not easy, probably need a loop
- Collection of all keys:
d.keys()
- Collection of all values:
d.values()
- Indices: there are none (just keys)
- List of all keys:
list( d.keys() )
- How do we look at the keys in a
dict
for key in d.keys():
# do something with key
- How do we look at the values of a
dict
for value in d.values():
# do something with value
- Trying to find and change a particular entry
- By key; e.g., change key
18
to"adult"
d[ 18 ] = "adult"
- By value (find key for value 18)
found = None
for key in d.keys():
value = d[ key ]
if value == 18:
found = key