Class 24 — Monday October 19

Reaching an understanding with functions

Functional living — Problem-solving strategy — Embrace this future


Look both ways


Agenda


Examples



Homework


Why functions


Module harb.py

Function add()

import harb

 

n1, n2 = 3, 14

n3, n4 = 15, 92

 

t1 = harb.add( n1, n2 )

t2 = harb.add( n3, n4 )

 

print( "add(", n1, ",", n2, "):", t1 )

print( "add(", n3, ",", n4, "):", t2 )

then the output should be

add( 3 , 14 ): 17

add( 15 , 92 ): 107

Function negate( x )

n5, n6 = -6, 53

 

i1 = harb.negate( n5 )

i2 = harb.negate( n6 )

 

print( "negate(", n5, "):", i1 )

print( "negate(", n6, "):", i2 )

then the output should be

negate( -6 ): 6

negate( 53 ): -53



Requirement


Terminoloy

import module_name

module_name . function_name ( arguments )

return function_result

def function_name( parameters ) :

  ''' header_comment

  '''

  action

def add( a, b ) : # function named add(), parameters named a and b

  ''' Returns value of a + b

  '''

 

  result = a + b # compute value of interest

 

  return result # function hands back its result


Taxonomy


Designing functions


Module olio.py

Function voting_age()

x = olio.voting_age()

y = olio.voting_age()

Function has_blanks( s )

x = 'CS 1112'

y = 'the_aarvark_said_arf_arf'

b1 = olio.has_blanks( x )

b2 = olio.has_blanks( y )

Function great_seal()

olio.great_seal( )

print()

olio.great_seal( )

print()

produces as output

E Pluribus Unum

E Pluribus Unum

Function a_ing( n )

olio.a_ing( 5 )

print()

olio.a_ing( 1 )

print()

olio.a_ing( 3 )

produces as output

a

aa

aaa

aaaa

aaaaa

a

a

aa

aaa

 


  © 2020 Jim Cohoon   Resources from previous semesters are available.