You are on page 1of 133

Functions and Control Flow

Adopted from Stanford Uni’s CS106ap course slides by Kylie Jue and Sonja Johnson-Yu
Today’s How do we teach Karel new things?

questions How do we handle different worlds?


1. Karel review


2. Karel functions


Today’s 
 3. Control flow


topics Conditionals (if)



Loops (while)


4. What’s next?
Remember Karel?
This is Karel’s world corners
(intersections)
walls
streets
 beepers
(rows)
avenues

(columns)
What Karel can do
move()

turn_left()

put_beeper()

pick_beeper()
What Karel can do

move()
Makes Karel move forward one
square in the direction it is facing.

Errors if there is a wall in front of


Karel.

begin end
What Karel can do

turn_left()
Makes Karel turn left.

begin end
What Karel can do

put_beeper()
Makes Karel place a beeper on
the corner where it is currently
standing.

You can place multiple beepers


on any given corner.
begin end
What Karel can do

pick_beeper()
Makes Karel pick up a beeper
from the corner where it is
currently standing.

Errors if there are no beepers


present on the corner.
begin end
Karel demo!
Karel Goes Home

begin end
Karel Goes Home turning right

turn_left()
turn_left()
turn_left()
Karel Goes Home

move()
Karel Goes Home

turn_left()
turn_left()
turn_left()
Karel Goes Home

move()
Karel Goes Home

turn_left()
Karel Goes Home

move()
Karel Goes Home

pick_beeper()
How could I talk to Karel using Python
The structure of a program
import ...

def main():
...

if __name__ == '__main__':
...
The structure of a program
import ... Definition

computer program
def main(): A set of instructions for the
... computer – an “app.” These
instructions are also called
if __name__ == '__main__': lines of “source code.”
...
The structure of a program
import ... import modules (more on that
later in the quarter)
def main():
...

if __name__ == '__main__':
...
The structure of a program

import ...

def main(): define functions


...

if __name__ == '__main__':
...
The structure of a program

import ...

def main():
...

if __name__ == '__main__':
call your main function (you
...
won’t need to worry about
this)
The structure of a program
import ...

def main(): This is where we’ve


...
been writing our code!
if __name__ == '__main__':
...
The structure of a program

def main():
...
This is where we’ve
been writing our code!
Karel Goes Home (solution)
def main():
# Climb wall
turn_left()
move()
turn_left()
turn_left()
turn_left()
move()
turn_left()
turn_left() Turning
turn_left()
move() right is
# Go home
turn_left()
move()
tedious!
pick_beeper()
How do we teach Karel new commands?
How do we teach Karel new commands?

Functions!
Definition
function
A smaller part of your program that solves a
specific sub-problem
Functions

● Smaller parts of your program that solve specific sub-


problems
○ By decomposing your program into many small
functions, your code becomes easier to read.
Functions

● Smaller parts of your program that solve a specific sub-


problems

● A function has two parts:


○ The function definition


○ One or more function calls


Functions

● Smaller parts of your program that solve a specific sub-


problems

● A function has two parts:


○ The function definition
What does the new Karel command do?


○ One or more function calls


Functions

● Smaller parts of your program that solve a specific sub-


problems

● A function has two parts:


○ The function definition
What does the new Karel command do?


○ One or more function calls



Where you tell Karel to actually do the command
Let’s revisit
KarelGoesHome.py
[demo]
Turning right
def turn_right():
“““
Makes Karel turn right.
”””
turn_left()
turn_left()
turn_left()
Turning right
def turn_right():
“““
Makes Karel turn right.
”””
turn_left()
turn_left()
turn_left()

def main():
...
turn_right()
...
Turning right
def turn_right():
“““
Makes Karel turn right. Function definition
”””
turn_left()
What does the new Karel
turn_left() command do?

turn_left()

def main():
...
turn_right()
...
Turning right
def turn_right():
“““
Makes Karel turn right.
”””
turn_left()
turn_left()
turn_left()

def main():
...
turn_right() Function call

... Where you tell Karel to
actually do the command

Turning right
“Go find the function
def turn_right():
“““ definition, do the
Makes Karel turn right. commands inside,
”””
turn_left() and come back
turn_left()
turn_left() when done.”
def main():
... Function call

turn_right() Where you tell Karel to
... actually do the command

General structure of
functions

[whiteboard]
The structure of a function
def my_function_name():
“““
Write a good description
for your function here.
”””
# Put other Karel commands here

...
def caller_function():
my_function_name() # Function call
The structure of a function
Definition
function [header]
def my_function_name(): comment
“““ Comment that describes
Write a good description
for your function here. what a function does
””” using “““...”””
# Put other Karel commands here

...
def caller_function():
my_function_name() # Function call
The structure of a function
Definition
inline comments
def my_function_name(): Comments that describe a
“““
specific, complex block of
Write a good description
for your function here. code using #
”””
# Put other Karel commands here

...
def caller_function():
my_function_name() # Function call
The structure of a function
def my_function_name():
“““
Write a good description
for your function here.
”””
# Put other Karel commands here
Make sure lines inside
...
def caller_function():
each function are indented
my_function_name() # Function call
The structure of a function
Style note
def my_function_name(): indentation
“““ Each level of indentation
Write a good description should be four spaces.
for your function here.
”””
# Put other Karel commands here
Make sure lines inside each
...
def caller_function(): function are indented
my_function_name() # Function call
The structure of a function Style note
function names
def my_function_name(): Separate words with
“““
Write a good description underscores and use
for your function here. verbs
”””
# Put other Karel commands here

...
def caller_function():
my_function_name() # Function call
The structure of a function
def my_function_name():
“““
Write a good description
for your function here.
”””
# Put other Karel commands here
Note: The caller function
...
def caller_function(): doesn’t have to be main()!
my_function_name() # Function call
Think/Pair/Share:

Write a function turn_around()


that makes Karel rotate 180 degrees.
Common issues

[demo]
“Syntax” errors (i.e. typos)

● Forgetting `()` or `:` in the function definition


○ Line number shows up in the error!


● Forgetting `()` in the function call


○ You get a warning (yellow underlining) instead of an
error here
“Syntax” errors (i.e. typos)

● Forgetting `()` or `:` in the function definition


○ Line number shows up in the error!


● Forgetting `()` in the function call


○ You get a warning (yellow underlining) instead of an
error here
These are super common, even for
professional programmers!
Common issues
bugs
Common issues
Definition
debugging
The process of finding and fixing errors
(syntactical or logical) in your code.
Most of your time will
be doing this!
Definition
debugging
The process of finding and fixing errors
(syntactical or logical) in your code.
How do we handle different worlds?
How do we handle different worlds?

Control flow!
Definition
control flow structures
Code features that affect the order, or flow, in
which the lines of code in a program happen
Conditionals

(if statements)
The if Statement
• Sequence structure: set of statements that execute in the order they appear
• Control structure: logical design that controls order in which set of statements
execute
• Decision structure: specific action(s) performed only if a condition exists

• Also known as selection structure


The if Statement (cont’d.)
• In flowchart, diamond represents true/false condition that must be
tested
• Actions can be conditionally executed

• Performed only when a condition is true


• Single alternative decision structure: provides only one alternative path
of execution

• If condition is not true, exit the structure


The if Statement (cont’d.)
If statements

if ___________:

# Do something
If statements

if ___________:

# Do something

Condition
If statements

if ___________:

# Do something

Condition

(any boolean
expression)
If statements

if ___________:

# Do something

Condition

(any boolean
expression)Definition
boolean expression
A code snippet that evaluates to True or False
If statements

if ___________:

# Do something

Condition

True False
If statements

if ___________:

# Do something

Condition

True False
If statements

if ___________:

# Do something

Condition

True False
If statements

if ___________:

# Do something
If statements

if ___________:

# Do something
If statements

if ___________:

# Do something
If statements

if the light is red:

Stop
The if Statement (cont’d.)
• Python syntax:

if condition:

Statement

Statement
• First line known as the if clause

• Includes the keyword if followed by condition

• The condition can be true or false

• When the if statement executes, the condition is tested, and if it is true the block
statements are executed. otherwise, block statements are skipped
Boolean Expressions and Relational Operators
• Boolean expression: expression tested by if statement to determine if it is true
or false

• Example: a > b

• true if a is greater than b; false otherwise


• Relational operator: determines whether a specific relationship exists between
two values

• Example: greater than (>)


Boolean Expressions and Relational Operators (cont’d.)
• >= and <= operators test more than one relationship

• It is enough for one of the relationships to exist for the expression to be true
• == operator determines whether the two operands are equal to one another

• Do not confuse with assignment operator (=)


• != operator determines whether the two operands are not equal
Boolean Expressions and Relational Operators (cont’d.)
Boolean Expressions and Relational Operators (cont’d.)
• Using a Boolean expression with the > relational operator
Boolean Expressions and Relational Operators (cont’d.)
• Any relational operator can be used in a decision block

• Example: if balance == 0

• Example: if payment != balance


• It is possible to have a block inside another block

• Example: if statement inside a function

• Statements in inner block must be indented with respect to the outer block
General structure of 

if statements

[whiteboard]
The structure of an if statement

if boolean expression:

# Do something when condition is True


The structure of an if statement

if boolean expression:

# Do something when condition is True

Make sure lines inside the if statement


are indented!
Boolean expressions in
Karel
Karel functions that evaluate to boolean expressions

front_is_clear() Is there no wall in front of Karel?


left_is_clear() Is there no wall to Karel’s left?
right_is_clear() Is there no wall to Karel’s right?
on_beeper() Is there a beeper on the corner where Karel is standing?
facing_north() Is Karel facing north?
facing_south() Is Karel facing south?
facing_east() Is Karel facing east?
facing_west() Is Karel facing west?
Karel functions that evaluate to boolean expressions

● These built-in Karel functions evaluate to:


○ True if the answer to the corresponding question is “yes”
○ False if the answer to the corresponding question is “no”


● You can find all of these in the Karel Reference Guide on the course
website.
Let’s bring it back to Karel:
move_safely()
[demo]
Loops

(while loops)
Before we had if statements...

if ___________:

# Do something
Before we had if statements...

if ___________:

# Do something

What if we want something to happen


multiple times?
Repetition Structures
• Often have to write code that performs the same task multiple times

• Disadvantages to duplicating code

• Makes program large

• Time consuming

• May need to be corrected in many places


• Repetition structure: makes computer repeat included code as necessary

• Includes condition-controlled loops and count-controlled loops


The while Loop: a Condition-Controlled Loop
• while loop: while condition is true, do something

• Two parts:

• Condition tested for true or false value

• Statements repeated as long as condition is true

• In flow chart, line goes back to previous part

• General format:

while condition:

statements
The while Loop: a Condition-Controlled Loop (cont’d.)
The while Loop: a Condition-Controlled Loop (cont’d.)
• In order for a loop to stop executing, something has to happen inside the loop
to make the condition false
• Iteration: one execution of the body of a loop
• while loop is known as a pretest loop

– Tests condition before performing an iteration

• Will never execute if condition is false to start with

• Requires performing some steps prior to the loop


While loops

while ___________:

# Do something
While loops

while ___________:

# Do something
Condition
While loops

while ___________:

# Do something
Condition

True False
While loops

while ___________: repeat if true


# Do something
Condition

True False
While loops

while ___________:

# Do something
Condition

True False
While loops

while ___________:

# Do something
While loops

while road is clear:

Drive forward
Let’s bring it back to Karel:

travel_row()
[demo]
General structure of 

while loops

[whiteboard]
The structure of a while loop

while boolean expression:

# Do something while condition is True


The structure of a while loop

while boolean expression:

# Do something while condition is True

Make sure lines inside the if statement


are indented!
Let’s bring it back to Karel:

travel_row()
Let’s bring it back to Karel:

travel_row()
Let’s bring it back to Karel:

make_beeper_row()
[demo]
Definition
fencepost problem (off-by-one bug)
An error in which your code performs a task
one too many or too few times.
Definition
fencepost problem (off-by-one bug)
An error in which your code performs a task
one too many or too few times.
Why?
Slide courtesy of Chris Piech
What if some corners
already have beepers?
What is some corners already have beepers?
Your turn to try!

make_beeper_row() (V2)

(tomorrow)
What if some corners already have beepers?

● Combine what we know about if and while!


● Potentially useful:
○ on_beeper()
○ not
While loop summary
(and misconceptions)
while loop summary

● All lines inside the while loop will run if the condition is true
while loop summary

● All lines inside the while loop will run if the condition is true


● Lines inside the while loop happen one at a time and in order
while loop summary

● All lines inside the while loop will run if the condition is true


● Lines inside the while loop happen one at a time and in order


● The condition is checked again only after all of the lines have run
while loop summary

● All lines inside the while loop will run if the condition is true


● Lines inside the while loop happen one at a time and in order


● The condition is checked again only after all of the lines have run

It’s a very common misconception to


expect the while loop to stop in the middle
when the condition is no longer true!
while loop summary

● All lines inside the while loop will run if the condition is true


● Lines inside the while loop happen one at a time and in order


● The condition is checked again only after all of the lines have run


● It is possible for the while loop body to run 0 times!


○ Just like with if statements
Common bugs

● Forgetting not
Common bugs

● Forgetting not

● Forgetting an if statement around the first put_beeper()


Common bugs

● Forgetting not

● Forgetting an if statement around the first put_beeper()

● Forgetting to call your function!



Common bugs

● Forgetting not

● Forgetting an if statement around the first put_beeper()

● Forgetting to call your function!


● Getting stuck in an infinite loop


Common bugs

● Forgetting not

● Forgetting an if statement around the first put_beeper()

● Forgetting to call your function!
 Definition


● Getting stuck in an infinite loop infinite loop
When your code gets stuck inside
a loop because the condition never
evaluates to false
Infinite Loops
• Loops must contain within themselves a way to terminate

• Something inside a while loop must eventually make the condition false
• Infinite loop: loop that does not have a way of stopping

• Repeats until program is interrupted

• Occurs when programmer forgets to include stopping code in the loop


Common bugs

● Forgetting not

● Forgetting an if statement around the first put_beeper()

● Forgetting to call your function!


● Getting stuck in an infinite loop


What’s next?
Next...

● Focus on writing good functions and good programs


● Practice breaking down complex Karel problems


● More examples of how Karel can represent real-world problems


Why do we use decomposition?
Next Lecture’s How might we approach breaking

questions down (decomposing) difficult


problems?

You might also like