You are on page 1of 2

● Function: a named group of instructions that can be used to solve a specific sub-problem

in a program
○ A program can be decomposed into a set of smaller sub-problems that are more
approachable than trying to solve the complete program
○ Programs are decomposed by defining functions to solve sub-problems
● Using functions requires two components
○ Function definition - Which instructions does Karel perform?
○ Function call(s) - Where does Karel perform the instructions in the program?

Sub-problem: Karel lacks instructions to make a right turn


Teach Karel how to turn right by using something Karel already knows how to do

Turn left three times = Turn right


Function Definition Function Call

def good_function_name():
‘“”’Write a good description of what your functions does.

pre-condition: What is the state of Karel’s world at beginning of function?


post-condition: What is the state of Karel’s world at end of function
‘“”’

# Write Karel instructions to be performed


def caller_function():
good_function_name() # Function call

def turn_around():
‘“”’Makes Karel turn around.

pre-condition: none
post-condition: Karel is facing the opposite direction of its starting position
‘“”’
turn_left()
turn_left()

control flow structures: language features that affect the order in which instructions are followed

If __________:
# perform these instructions

________ is a boolean statement


If condition is True:
Instructions are performed
If condition is False:
Instructions are not performed

def move_safely():
‘“”’Makes Karel move forward when Karel’s front is clear (no wall blocking point)
pre-condition: None
post-condition: Karel moves forward
‘“”’
If front_is_clear()
move()

Don’t solve the example; Solve the problem

def travel_row():
‘“”’Makes Karel move forward until front is blocked by a wall
pre-condition: Karel is facing East or West
post-condition: Karel travels to the end of the row
‘“”’
while boolean expression:
#perform instructions when condition is true

You might also like