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)

Comments

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

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

Built-in commands

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

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

Show it to me, Let me do it

Before...

Before…

..and after.

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

Show it to me

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.

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,

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.

Show me

Before...

Before…

..and after.

..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.

Graduation from level

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.

Before: Ready!

Before: Ready!

After: Touchdown!

After: Touchdown!

Answer: Show it to me

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:

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:

The other two of functions are also fairly simple:

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:

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

Before: Ready to plant the strawberries


After: All done

After: All done

Answer: Show it to me

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:

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:

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:

Version 2:

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:

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

Work it out

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:

turn_around

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

fertilizer tryout

Answer: Show it to me

Before: Ready to move these bags.

Before: Ready to move these bags.

After: Uff.. that was difficult.

After: Uff.. that was difficult.

Hint:

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

1.2 Olympic dreams – Obstacle course

★★ Work it out

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:

or, graphically:

sidestep_left()
sidestep_right

Use these functions to take Karel home.

Answer: Show it to me

Before...

Before…

..and after.

..and after.

Hint:

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

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

Image from vegetable-garden-basics.com

Answer: Show it to me

Before...

Before…

..and after

..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

“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

Answer: Show it to me

Before...

Before…

..and after

..and after