Class 30 — November 6

Part two is ending — Soon time to show mastery — Expect to do well

Functioning


Look both aways


Agenda


Come on down

question


question

Accomodations


What to expect for the test


List patterns — suppose alist, blist, and clist are lists and that value v is not a list

result = ...

for element in alist :

  ...

return result

n = len( alist )

for i in range( 0, n ) :

  element = alist[ i ]

  ...

  alist[ i ] = element

  • Appends v to end of alist.
  • Removes first occurence of v from alist.
  • Index of first occurrence of v in alist.
  • Concatenates alist and blist to make clist.
  • Removes the last element from alist. The value of that former element is the return value assigned to v.
  • Removes the element at index i from alist. The value of that former element is the return value assigned to v.

blist = alist + v # cannot add a list and a non-list

blist = alist + [ v ] # can add a list with another list


Functions

  • A return statement can optionally have a return expression following the keyword return. 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 returns None.

Warnings


Gotchas

`* Nested for-loops usually wrong unless using a list-of-lists (e.g., a dataset) or looking at one list in relation to another liset


Miscellaneous syntheses of past Q & A

Argument versus parameter


print() versus return

def f( x ) :

  print( x )

This function displays the value of x and returns None

def g( x ) :

  return x

This function does no display and returns the value of its parameter


How can a function change the contents of argument memory?

def h ( my_list, my_dictionary ) :

  my_list[ index ] = ...

  my_list.remove( ... )

  my_list.append( ... )

  my_list.pop( ... )

  my_list.sort()

  my_dictionary[ key ] = value

def f( x ) :

  y = x

  y.pop()

No! The assignment of x to y means modifying y affects x

def f( x ) :

  y = x[ : ] # or y = list( x ) or y = x.copy()

  y.pop()

Yes! The assignment to y makes it a copy of x and not x itself


Function sort() versus sorted():


Dictionaries

d = {} # empty dict

d = { 18 : 'voting', 67 : 'retirement', 'eighteen' : 18}

d[ 100 ] = 'centarian' # makes association for key 100 to be 'centarian'

for key in d.keys():

  # do something with key

for value in d.values():

  # do something with value

d[ 18 ] = 'adult'

found = None

for key in d.keys():

  value = d[ key ]

  if value == 18:

  found = key



q & a session with jb

 


 

 

 
   
   
   
 
  © 2019 Jim Cohoon   Resources from previous semesters are available.