Title: Flow Control
1Flow Control
So far, our programs have been simple...
function area circle_area( radius ) function
area circle_area( radius ) area pi radius2
Are functions just shorthand?
No! They can be much more powerful... with Flow
Control.
2Flow Control?
'Flow control' can sound a little odd at first....
But it makes sense we want to control the flow
of evaluation. Which means...
inputs
function
outputs
3Decisions
Execute one piece of code instead of another if
some thing is true
Example How to make your experiment work
if isGoodForMe( subject.data ) keepInStudy(
subject ) else throwOutSubject( subject ) end
Now the program branches... more than one
possible execution path.
if-statements are called conditionals.
4Repetitions
We may want to do something more than once.
So we use loops...
While Loop
For Loop
for indexbeginincrend expressions end
while condition expressions end
5While
While loops evaluate statements while something
is true.
Count 'e' in a string str 'Sleeplessness' num
_e 0 index 1 while index lt
length(str) if str(index) 'e' num_e
num_e 1 end index index 1 end
6For
For loops iterate though values of an index
Count 'e' in a string str 'Sleeplessness' num
_e 0 for index1length(str) if str(index)
'e' num_e num_e 1 end end
7More Control
We are able to control how loops execute
- continue skip the rest and start a new loop.
- break stop executing the loop and go to the end.
n 0 x 0 while n lt 10 n n 1 if n lt
5 continue end break end
8Things we know
- Code can branch using if statements.
- Code can repeat using loops
- while loops execute while a condition is true.
- for loops iterate over a set of values.
- continue starts over.
- break ends.