4 – function I/O

“Think twice; code once”

Theory

The value of a function

The value of a function is the value that the function returns, i.e., the value that follows the keyword return.

In Python, if the keyword return is not followed by anything, then the value of the function is set to the special value None. For example,

let me try it

# function w/o a return so its value is None
def greet():
    print( "Hello" )

# integer function with a value of 15
def sum_1_to_5():
    return 1 + 2 + 3 + 4 + 5

# string function with a value of "Hello world"
def greet():
    return "Hello" + " " + "world"

Function Input/Output (I/O)

output

To get information from a function, we assign its value to a variable, e.g.,

age = int( "12" )                       # age is an integer variable
name = input( "what is your name? " )   # name is a string variable

input

We pass information to a function within the parentheses; the data in the parentheses are called the arguments of the function call, e.g.,

move()              # call with no arguments
print( "hello" )    # call with a single arg: the string "hello"
repeat( move, 10 )  # call with two args: the name of
                    # the function 'move' and the integer 10

minus_diagramFunctions receive data in variables called parameters. The parameters are paired up with the arguments so that:

1st parameter = 1st argument
2nd parameter = 2nd argument

and so on

For example:

let me try

# the parameters of add_3 are 'a', 'b', and 'c'
def add_3( a, b, c ):
    the_sum = a + b + c
    return the_sum

# main program
savings = 25
allowance = 10
tooth_fairy = 10

# args of  call are 'savings', 'allowance', and 'tooth_fairy'
# assign 'the_sum' to the variable 'cash'
cash = add_3( savings, allowance, tooth_fairy )
say( "I have $" + str(cash) )

Training Missions

4.TM1 Life in SoCal – Happy Birthday, Karel

Work it out

Karel is having a Birthday party and wants to invite his friends. Write the function

invite( friend )

that receives a string with the name of the friend and returns a string with the following message:

“Dear <friend>, party tomorrow at my house at 3:00pm. Karel”

where <friend> needs to be replaced with the name of the friend.

The main program is ready to print all the invitations to Karel’s diary:

# main program
print( invite( "R2D2" ) )
print( invite( "C3PO" ) )
print( invite( "Eve" ) )
print( invite( "Wall-E" ) )

All we are missing is the invite() function.

Birthday cake-01

Answer: Show it to me

4.TM1 Life in SoCal – Football

Work it out

It is no surprise that a football player as skilled as Karel is being courted to play in different leagues. The canadian football fields are larger than the american ones. Help Karel run some reconnaissance on the perimeter of each field. Most of the program is already written; we need to write the functions that find the perimeter and announce the result.

American football field

American football field

The perimeter of a rectangle is the sum of the length of all its sides, e.g., if its width it 5 ft. and its length is 10 ft. then its perimeter is:

perimeter = 2 * 5 + 2 * 10    # asterisk * is multiplication
          = 30                # 30 ft.

Answer: Show it to me

def rectangle_perimeter( width, height ):
    # the asterisk * is the multiplication operator
    perimeter = 2 * width + 2 * height    
    return perimeter

def announce( league, perimeter ):
    msg = "The " + league + " field has a perimeter of "
    msg = msg +  str(perimeter) + " ft."
    print( msg )

# main program
league_1 = "National football league"
w = 160  # ft.
h = 360   # ft.
nfl_perim = rectangle_perimeter( w, h ) 

league_2 = "Canadian football league"
w = 195  # ft.
h = 450   # ft.
canadian_perim = rectangle_perimeter( w, h )

announce( league_1, nfl_perim )
announce( league_2, canadian_perim )

3.1 Strawberries – Fertilizer tryout

Work it out

Karel is trying out a new fertilizer. The manufacturer left 50 bags for Karel but we only need a few of them. Use input() to tell Karel a number between 0 and 50; he needs to move these many bags to the shed, then go home, and then use say() to confirm the number of bags that he moved to the shed.

fertilizer tryout

Answer: Show it to me

We ask Karel to take 12 bags to the shed

We ask Karel to take 12 bags to the shed


Job well done

Job well done

3.2 Strawberries – Single file

★★ Work it out

Karel wants to plant strawberry plants in each of the 7 cells in front of his house. This time, though, he has a strategy for planting them: he will place 1 plant in the farthest cell from his house and then, as he approaches the house, he will place one more plant in each cell than he placed in the preceding cell, i.e., he will plant, 1, 2, 3, 4, 5, 6, and 7 plants in the 7 cells in front of his house. Keep track of how many strawberries he has planted and announce the total when he gets home.

Notice the pattern: if he deposited i plants in a cell, Karel will deposit i+1 plants in the next cell, i.e.,
1, 2, 3, 4, 5, etc.

Strawberry, ''gariguette'' variety Copyright © 2005 David Monniaux

Strawberry, ”gariguette” variety Copyright © 2005 David Monniaux

Answer: Show it to me

Plant the strawberries in front of the house

Plant the strawberries in front of the house

Ha!  Done.

Ha! Done.

3.3 Strawberries – single file harvest

★★★ Work it out

The strategy of Karel worked out: it turns out that the more plants you put together, the more strawberries you get; in each grid we got the square of the number of plants that we initially planted, i.e., if we planted 5 plants, we got 5 x 5 = 25 strawberries; if we planted 6, we got 6 x 6 = 36 strawberries, and so on.

Notice the pattern: if he picked up i plants from a cell, Karel will picked up i*i plants from the next cell, i.e., 1, 4, 9, 16, 25, …

Have Karel pick up all the strawberries and put 120 in the fridge, in the shed. The rest he takes home to bake a pie.

"Strawberry Cheese Pie" by Own work - Own work. Licensed under Creative Commons Attribution 2.5 via Wikimedia Commons

“Strawberry Cheese Pie” by Own work – Own work. Licensed under Creative Commons Attribution 2.5 via Wikimedia Commons

Answer: Show it to me

Collect the strawberries, put 120 in the shed and take the rest home to bake a pie.

Collect the strawberries, put 120 in the shed and take the rest home to bake a pie.

Final scenario

Final scenario

Optional Mission – Does not give a star

3.4 Life in SoCal – Binary harvest

★★★★ Work it out

Karel is encouraged by his success with the single line crop and increasing crop sizes. He has bought fertilizer to follow this strategy further. He bought lots of fertilizer of increasing size, this time each twice as big as the previous one, i.e., lots of 1, 2, 4, 8, 16, … etc. Please, move the bags to the sheds and go home to announce how many bags we got in total.

Notice the pattern: if he move i bags to a shed, Karel will move i+i bags to the next shed, i.e., 1, 2, 4, 8, 16, …

Image from vegetable-garden-basics.com

Image from vegetable-garden-basics.com

Answer: Show it to me

Before

Before

..and after

..and after