# 2 – For loops

“We can solve a complex problem
by breaking it apart and putting together
the solutions to the pieces.”

# Theory

## For loop

With repeat() we can repeat a single function many times, e.g.,

repeat( move, 4 )


With for loops we can repeat a group of instructions many times. For example, the following two pieces of code do the same thing:

for i in range( 0, 4 ):
move()
put()


move() # 1 time
put()

move() #2 times
put()

move() # 3 times
put()

move() # 4 times
put()


The technique of replacing a loop for what it actually does is called “unrolling” the loop.

## Libraries

A library is a collection of functions that we can load in our program and use as if we had written them. The editor of Karel has two tabs: “Python code” and “Library”. The “Library” tab shows us the contents of a library called my_lib.

Libraries contain functions that are useful for many programs. In this level we will find the following functions in the my_lib library:

left()
right()
turn_around()
sidestep_left()
sidestep_right()


In Python, we load all the functions in a library importing it as follows:

from my_lib import  *      # load all functions in the library 'my_lib'


The star after the word import is called an asterisk and it means ‘everything’. In U.S. keyboards we can type it using shift-8 (i.e., press the shift key and then press the number 8). Leave a space between the word import and the asterisk.

## Divide and conquer

To split a problem into functions, look for opportunities to…

1. …to split a problem in independent parts
2. …to describe a pattern.

We must learn to see the problem from both the point of view of Karel and from ours. Karel has a ground view of the scene; we have a bird’s eye view of it. It is often the case that the solution to a problem is much easier in one of these views than in the other.

Karel’s point of view (ground view)

Our point of view (bird’s eye view)

# Training Missions

## 2.TM1 Strawberries – Symmetry

Work it out

Karel is at home admiring his garden. Having strawberries only on the north stalls hurts his sense of symmetry. Please, help Karel move half of the plants in the north stalls to the south stalls and then take him back home and have him face the garden again.

Strawberry rows – Image from WashingtonFarms.net

Before…

..and after

Hint:

Use the library! To import the functions of the library into your program use

from my_lib import  *

This mission is about describing the pattern and then going home. The main function could be something like:

# main program
repeat( transfer_plant, 7 )
go_home()


## 2.TM2 Olympic dreams – Mountain Training

Work it out

Karel has been promised a spot on the downhill team if he is able to show that his legs have the strength necessary to cut it. The coach has signed us up for mountain training. Karel needs to climb the mountain, pick up some dumbbells on the way down, leave them at the base of the mountain, and then go home. It goes without saying that Karel cannot fly; he has to go up and down the steps.

Jenny Hadfield – Image from runnersworld.com

Before…

…and after.

Hint:

Use the library! To import the functions of the library into your program use

from my_lib import  *

This mission is about describing the pattern and then going home. The main function could be something like:

# main program
climb()
descend()
repeat( put, 10 )
move()


# In-class Mission Instructions

Hello again, Youngling. You and your droid are half way through the most important part of your training: how to break programs into functions. Hence, you need to keep in mind the rules to write good functions:

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

The rules of how to solve a problem and get credit for it still stand:

• 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 at any time.

The use of the library requires adding two more rules:

• Do not modify the library in any way.
• Code in the library does not count towards the max. of 30 lines.

Keep up the good work, Youngling. You are almost there.

## 2.1 Olympic dreams – Downhill

Sweet! (Karel doing happy dance here). The mountain training paid off big time: Karel is on the downhill team. Take Karel down the hill, weaving between the flags, to the trophy presentation room (or, depending on our programming skills, to the first-aid station).

“Andrej Šporn at the 2010 Winter Olympic downhill” by Jon Wick – originally posted to Flickr as Go Time. Licensed under Creative Commons Attribution 2.0 via Wikimedia Commons

Before…

…and after.

## 2.2 Strawberries – Strawberry fields

Wow! Karel has been busy. Look at all the strawberries in his strawberry patch. Harvest all the plants and take Karel home.

Feel free to use the functions from the library.

“Strawberry harvest at Louisiana State Exhibit Museum in Shreveport IMG 3360” by Billy Hathorn – Own work. Licensed under Creative Commons Attribution-Share Alike 3.0 via Wikimedia Commons

Before..

..and after.

Hint:

We can split the collection of the 6 rows into three sets of two, with each of the sets consisting of a run going up followed by a run going down, as shown on the right.

Another possibility is to have 6 identical runs.

Collecting berries in both directions

## 2.3 Life in SoCal – Softball coach

★★★ Work it out

Karel is volunteering to coach the local Pee-Wee softball team. He has to arrive to the field before anyone else and paint the lines between the bases that form the diamond, i.e., he has to put a token in each of the cells in the diagonal between the bases. Karel arrives to the field with 12 tokens in his bag. Help him paint the lines and then take him home.

Before…

…and after.

Hint:

This problem is similar to the speed skating mission. The difference is that the square is inclined 45°..

Pattern for softball coach

# Optional Mission – Does not give a star

## 2.4 Olympic dreams – Hockey me this

★★★★ Work it out

This had never happened!… The hockey final between the U.S.A. and Russia was stopped after 12 overtimes. The olympic committee debated and arrived to a decision: one way or another the game has to be decided tonight. To avoid a scandalous win via a coin toss, each team will select a player to demonstrate his skill by performing an extremely complicated move; the team whose player completes the maneuver will be the winner of the gold medal.

The chosen player has to skate a lap around the rink following a set of cones. There is no need to collect the cones.

“Ice Hockey sharks ducks” by Elliot – http://www.flickr.com/photos/pointnshoot/1426010816/. Licensed under Creative Commons Attribution 2.0 via Wikimedia Commons

The U.S.A. team has chosen Karel. Will he pull it off? Have Karel complete the figure and then enter the home square to receive the standing ovation.