Syntheses of past Q & A


Miscellaneous


Argument versus parameter


Parts of function


Local variable


When do functions have error versus None as output?


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():


Consider

def g( x ) :

  x = [ 1112 ]

x = [3,1,4]

g( x )

Neither x nor its contents have changed

def g( x ) :

  x = [ 1112 ]

  return x

x = [3,1,4]

y = x

x = g( x )

Then because of the return, x has changed; i.e., it points to a different list

Also, y has not changed

def g( x ) :

  x = [ 1112 ]

x = [ 3, 1, 4 ]

y = x

x = g( x )

Then x is None

Also, y has not changed


Invocation (examples)

len( x )

math.sqrt( 4 )

sorted( x )

math.sqrt( len( x ) )

f( x )

f()

def f(): # not an invocation

  return 3 # not an invocation

g = f # not an invocation (and probably a typo)

g = f() # an invocation

s = 'hi there' # not an invocation

s.lower # not an invocation

s.lower() # an invocation, but does not change anything...

s = s.lower() # an invocation, and probably what you meant to write


Invocation versus argument


While loops examples

x = 3

while ( x > 0 ) :

  x = x - 1


text = input( 'Type the third positive integer: ' )

while ( text != '3' ) :

  text = input( 'Type the third positive integer: ' )


while ( 2 < 3 ) :

  print( 'this will print again and again forever' )


while 2 > 3:

  print( 'this will never be printed' )


Dictionaries

d = {} # empty dict

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

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

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