# 1 – Functions

“A program is a recipe of how to do something complex
A function is a recipe of how to do something simple
Complexity is built on simplicity
Programs are built on functions.”

# Theory

## Introducing Python

We will use Python, a very popular computer language; it is often used as a first language but this does not mean that it is not powerful. Python was named “Computer Language of the Year” twice, in 2007 and 2010, and is used extensively is academia, research and industry. It consistently ranks among the top 10 most popular languages.

A very good place to try it out online is repl.it.

## Our robot simulator

Our simulator is called Reeborg and was written by André Roberge, a Canadian Physicist. He is very nice and has been particularly nice with our class at PCR; many of the features that we find in Reeborg today are the result of feedback from our classes at PCR. He would welcome a note from a PCR student thanking him from his efforts (andre.roberge@gmail.com)

A comment is text that is not part of the program; it has information for the programmer, not for the computer, i.e., it is like a margin note.

In Python, any text that follows a hashmark # is a comment:

Show it to me

# This is my first program
# Python ignores blank lines and
# everything in a line that follows a #

move()    # this is also a comment


## Data types

We will use three types of data:

• Booleans: the values True and False. We represent them as <bool>, i.e., True
• integers: an integer number. We represent them as <int>, e.g., 0, -5, 42
• strings: any sequence of 0 or more characters between double quotes. We represent them as <str>, e.g., “Hello”

## System commands

The following are a few functions that will appear often in our missions.

• sound( <bool> ): takes a boolean to turn the sound effects on and off
• think( <int> ): takes an integer to set a delay in milliseconds between commands, i.e., a value of 1000 sets a delay of 1 second. The minimum value is 0. Delays of 250 or less turn off the sound effects.
• say( <str> or <int> or <bool> ): pops up an alert window with the value of a boolean or an integer or a string
• print( <str> or <int> or <bool> ): writes a boolean or an integer or a string in Karel’s console
• pause(): pauses the program until we press the play or step buttons

For example:

Let me do it

sound( True )              # turn on the sound effects
think( 1000 )              # set delay to 1 second

print( "starting the program" )  # write to console
say( "moving slow" )             # write to screen
move()
move()
move()

say( "Pausing... press play to continue" ) # write to screen
pause()           # press play or step to continue

move()
move()
move()
print( "Bye bye" ) # write to  console


## Built-in commands

An actuation command (or function) is one that allows a robot to act. Karel has 4 built-in actuation functions:

move()       # move to the grid cell in front of the droid
turn_left()  # do a 90° military turn to the left (in place)
take()       # pick a token from the floor and put in his bag
put()        # get a token from his bag and put it on the floor


For example. Have Karel take the yellow token, place it in the empty slot and then take him to his home square:

sound( True )
think( 900 )

# take the token
say( "taking the token" )
move()
take()

# put the token
say( "putting the token" )
turn_left()
move()
put()

# go to the home square
say( "going home" )
move()

say( "done" )


Before…

..and after.

A mission fails if…
…we crash the droid against a wall
…we ask him to take a token while standing on an empty grid cell
…we ask him to put a token but the token bag is empty

## Repeat

To repeat a single command, we can use repeat():

repeat( command, n )  # repeat command n times


Show it to me

repeat( move, 8 )     # move 8 times


## Custom functions

Custom functions are mini-programs inside our program that we can call ‘later’.

Functions are important because we can use them to split a problem in independent parts

Karel ignores a function until we ‘call’ it.

def foo( ):       # define a function name 'foo'
command_1     # start of the body of the function
command_2     # in Python commands in the body are indented 4 spaces
....
command_n     # end of the body of the function

foo()             # calling the function foo()


A function returns to its caller when it it runs out of instructions.

The concept of a function is the single most important concept that you will learn in programming. Since this is of the utmost importance, we’ll spell it out for you:

DO

…have your functions do only one thing and one thing only
…keep your functions short; the best functions are a few lines long
…give your functions a meaningful name so that anyone can understand what they do

and DO NOT

…have your functions do multiple things
…write page-long functions
…give your functions names that only make sense to you

## Aliases

A function is an alias of another function if it is simply renaming it. For example,

def left():          # when left() is called ....
turn_left()      # it, in turn, calls turn_left()


left() is an alias of turn_left() because all left() does is to call turn_left().

## Programs

The commands are ran as they are written, from top to bottom, ignoring blank lines. Functions are not run until they are called.

When we run a program and Python finds a function that it is not part of the language, it checks whether it is a custom function that we defined. If he finds it, he stops what he is doing, runs the function, and then comes back to continue from where it left off.

sound( True )
think( 900 )

def take_the_token():
say( "taking the token" )
move()
take()

def put_the_token():
say( "putting the token" )
turn_left()
move()
put()

def go_to_home_square():
say( "going home" )
move()

# main program
take_the_token()
put_the_token()
go_to_home_square()
say( "done" )


Before…

..and after.

## Mission types

A mission can be one of three types:

• Training mission: one for which we should study the answer before trying to solve it ourselves.
• In-class mission: one for which we should try to solve it on our own, either in class or at home, before looking at the answer.
• Optional mission: you want to challenge yourself? Optional missions are not needed to finish the level and we do not get credit for them but often they will be the most interesting ones.

In class, we should try to work out the Deployment missions. If we are done with them, we could either work on the optional mission or start reading the theory of the next level. Please, do not work on optional missions in class unless you have already finished the missions scheduled for that day.

We do not get credit for finishing training missions. To get credit for in-class, we must submit them using the Submission form. If we have questions, we can get them answered using the Question form. In both cases, you must submit the mission using an email that we can reply to, i.e., one different from the lcusd.net account.

• We have solved a mission when we can write the solution from scratch without looking at the answer
• A solution must be 30 lines of code or shorter.
• To graduate from the level, submit solutions to all the 3 in-class missions.

# Training Missions

## 1.TM1 Life in SoCal – Touchdown

Work it out

In this mission we will use functions to split a problem in independent parts.

Karel needs to pick up the football and score a touchdown.

The green square is the home square. The yellow token represents the ball. The empty circle at home indicates with a ‘1’ by its side indicates that at the end of the mission there should be 1 token there.

After: Touchdown!

Our main function has to move Karel to the ball, have him take it, then move Karel to the end zone and, finally, have him put the ball down. The following program solves the mission completely:

# main function
go_to_ball()
pick_ball_up()
go_to_endzone()
score()


Now all we have to do is work of the details, i.e., we need to create a function for each of our commands using built-in and custom functions. Two of our functions are aliases:

def pick_ball_up():
take()

def score():
put()


The other two of functions are also fairly simple:

def go_to_ball():
repeat( move, 3 )

def go_to_endzone():
repeat( move, 6 )


To get the final program, we put our functions together with the main program. The order in which we place our functions is not important as long as the main function is last:

def go_to_ball():
repeat( move, 3 )

def go_to_endzone():
repeat( move, 6 )

def pick_ball_up():
take()

def score():
put()

# main function
go_to_ball()
pick_ball_up()
go_to_endzone()
score()


## 1.TM2 Strawberries – Single file

Work it out

In this mission we will use functions to describe a pattern.

Karel wants to plant 10 strawberry plants in each of the 7 cells in front of his house. Karel starts with 70 plants in his bag. Help Karel be the best farmer he can be and then take him home.

Before: Ready to plant the strawberries

After: All done

Our main function has to turn Karel to the right, then plant all the strawberries and then go home. The following program solves the mission completely:

# main function
right()
plant_berries()
go_home()


Now let’s work out the secondary functions. There is no command to turn right but we can effectively turn right if we turn left three times. To make the program more readable, we’ll write an alias to turn_left() and use it to write our right() function:

def left():
turn_left()

def right():
repeat( left, 3 )


There are two ways in which we can plant the strawberries. In the first one, we spell out what Karel needs to do; in the second one, we look for the pattern, write a function that describes it, and then use the function. Clearly, the second approach is better than the first:

Version 1:

def pick_up_berries():
move()
repeat( put, 10 )
move()
repeat( put, 10 )
move()
repeat( put, 10 )
move()
repeat( put, 10 )
move()
repeat( put, 10 )
move()
repeat( put, 10 )
move()
repeat( put, 10 )


Version 2:

def move_and_put():
move()
repeat( put, 10 )

def plant_berries():
repeat( move_and_put, 7 )


After picking up the berries Karel will be in the cell to the left of the home square. Hence, go_home() is simply an alias of move(). The complete final program is:

def left():
turn_left()

def right():
repeat( left, 3 )

def move_and_put():
move()
repeat( put, 10 )

def plant_berries():
repeat( move_and_put, 7 )

def go_home():
move()

# main function
right()
plant_berries()
go_home()


# In-class mission Instructions

Pay attention, Youngling!

Karel and you are a team and we are counting on you to train that droid. Now that you are about to be deployed in the field here are some suggestions:

• Learn to put yourself in the body of the robot. When you imagine yourself in its body, all the moves and turns make sense.
• The paper and pencil are your friends. The better prepared you are before you press that ‘play’ button for the first time, the faster you’ll finish the mission.
• Try to solve the missions correctly at the first try. We do not want to see you crashing Karel every time you code a move() command. No coding by trial-and-error here. Karel is a precision machine, not your personal punching bag.

## Integrity

Heads up because we will say this only one time. You are starting a path in which your integrity will be tested and you will be the judge. Move to the next level once you graduate, not before. If you cheat, you will not learn, but the real issue is that you will have practiced cheating, and we become really really good at whatever we practice. If you cheat in these lessons, you will be more inclined to cheat when something important comes along.

The levels ahead are much more challenging than this one… after all that is the point: if we are not challenged and do not struggle, we are not learning new concepts. If you get stuck, work hard at it; if you can’t figure it out on your own after a decent effort ask for help.

Making mistakes and being frustrated is part of the learning process. However, if and only if you have already struggled with the mission and are completely stuck, you are allowed and encouraged to peek at the answer, but not to copy it. Peeking at the answer will only be helpful if you have put an effort beforehand so you can appreciate it.

Good luck. Take care of that droid.

# In-class Missions

## 1.1 Strawberries – Fertilizer tryout

The strawberries deplete the nutrients from the soil at an alarming rate. Karel ordered 10 bags of fertilizer (the 10 yellow tokens) to try it out. Please, write the function turn_around() that turns Karel around:

and use it to move the fertilizer to the shed (the cell with the 10 empty slots) and take Karel home.

Before: Ready to move these bags.

After: Uff.. that was difficult.

Hint:

Use functions to split the mission in independent parts. The main function could be something like this:

# main program
pick_up_bags()
put_bags_in_shed()
go_home()


## 1.2 Olympic dreams – Obstacle course

This year Karel has a chance to join the Winter Olympic team. To improve his timing and balance, he set up an obstacle course in front of his house. We need to write the following routines:

sidestep_left()     # move to cell on left, face in original dir
sidestep_right()    # move to cell on right, face in original dir


or, graphically:

Use these functions to take Karel home.

Before…

..and after.

Hint:

Use a function to describe the pattern. The main function could be something like this:

# main program
repeat (up_and_down, 5)


## 1.3 Strawberries – Fertilizer

★★★ Work it out

Well.. the fertilizer worked. Karel just got an order of 8 pallets of 10 bags each, all of which have to be stored in their corresponding sheds. Nasty work but it we want strawberry shortcake we need the strawberries so….

Image from vegetable-garden-basics.com

Before…

..and after

Hint:

Use a function to describe the pattern.

# Optional Mission – Does not give a star

## 1.4 Olympic dreams – Speed skating

★★★★ Work it out

You cannot imagine the problem of fitting Karel with skates.. oh well. Karel is heading to the speed skating track: a single clove-shaped lap. Pick up all the 16 flags and then drop them at the podium. Will it be a medal or a contusion?

This is your chance to medal. Good luck.

“Paulien van Deutekom (08-12-2007)” by McSmit – Own work. Licensed under Creative Commons Attribution-Share Alike 3.0-2.5-2.0-1.0 via Wikimedia Commons