COMP1730/COMP6730 Programming for Scientists
Control, part 2: Iteration
Outline
* Iteration: The while statement * Simulations.
* Common problems with loops.
Iteration
Program control flow
Images from Punch & Enbody
Iteration
while test: statement
statement UNTIL …
statement
…
while test: statement statement
…
statement
…
* Iteration repeats a suite of statements.
* A test is evaluated before each iteration, and the suite executed (again) if it is true.
Iteration statements in python
* The while loop repeats a suite of statements as long as a condition is true.
* The for loop iterates through the elements of a collection or sequence (data structure) and executes a suite once for each element.
– We’ll come back to the for loop later in the course.
The while loop statement
while test expression : suite
statement(s)
1. Evaluate the test expression (converting the value to type bool if necessary).
2. If the value is True, execute the suite once, then go back to 1.
3. If the value is False, skip the suite and go on to the following statements (if any).
Suites (reminder)
* A suite is a (sub-)sequence of statements.
* A suite must contain at least one statement! * In python, a suite is delimited by indentation.
– All statements in the suite must be preceded by the same number of spaces/tabs (standard is 4 spaces).
– The indentation depth of the suite following if / else / while : must be greater than that of the statement.
* A suite can include nested suites (if’s, etc).
Variable assignment (reminder)
* A variable is a name that is associated with a value in the program.
* Variable assignment is a statement: var name = expression
– Note: Equality is written == (two =’s).
* A name–value association is created by the first
assignment to the name;
* subsequent assignments to the same name change the associated value.
* For example,
an int = 3 + 2 (From pythontutor.com)
anint = anint * 5
1. Evaluate expression 3 + 2 to 5.
2. Store value 5 with name an int
3. Evaluate expression an int * 5 to 25.
4. Store value 25 with name an int, replacing the previous associated value.
Problem: Counting boxes
* How many boxes are in the stack from the box in front of the sensor and up?
* While robot.sense color() != ’’, move the lift up, and count how many times; then move the lift down that many times.
def count boxes(): num boxes = 0
while robot.sense color() != ’’: num boxes = num boxes + 1 robot.lift up()
steps to go = num boxes while steps to go > 0:
robot.lift down()
stepstogo = stepstogo – 1 return num boxes
Problem: Solving an equation
* Solve f(x) = 0.
* The interval-halving algorithm:
– iff(m)≈0,returnm; – iff(m)<0,setl tom; - iff(m)>0,setutom.
return from a loop
* A loop (while or for) can appear in a function suite, and a return statement can appear in the suite of the loop.
def find box(color):
while robot.sense color() != ’’:
if robot.sense color() == color: return True
robot.lift up() return False
* Executing the return statement ends the function call, and therefore also exits the loop.
Simulation
Problem: How high does the Falcon 9 fly?
* Acceleration is thrust (force) divided by mass.
* 90%–96% of mass is fuel.
* Rocket’s engines have about 7.5% more thrust in vacuum than at sea level.
Image by SPACEX
Simulation
* Approximate the evolution of a complex of coupled processes.
* Simulate time by small steps (δt):
– At each step, compute the change in each variable over δt using the current values of
other variables.
Example: Rocket simulation
* Altitude (a): δa = v · δt
* Velocity (v ): δv = acceleration ·δt * acceleration = (thrust(a)/m) − g
– assuming thrust(a) grows linearly between sea level pressure and vaccuum (probably wrong).
* Mass (m):
– at time 0, m = take-off weight.
– δm=−B·δt.
– burn rate B = take-off fuel weight / burn time.
Example: The Competitive Lotka-Volterra model of ecology
* The change in the population of species i is δx /δt = r x 1 − xi +j̸=i aij xj
i ii Ki
where
– ri is the inherent growth rate of species i; – aij is the (negative) effect of species j on
species i;
– Ki is the population of species i that the
environment can support (“carrying capacity”).
Writing and debugging loops
Repeat while condition is true
* A while loop repeats as long as the condition (test expression) evaluates to True.
* If the condition is initially False, the loop executes zero times.
* If no variable involved in the condition is changed during execution of the suite, the value of the condition will not change, and the loop will continue forever.
Common problems with while loops
* Loop never starts: the control variable is not initialised correctly.
# find smallest divisor of num: i=1
while num % i != 0:
i=i+1
– num % 1isalways0!
Common problems with while loops
* Loop never ends: the control variable is not updated in the loop suite, or not updated in a way that can make the condition false.
i=0
while i != stop num:
i = i + step size
– What if stop num < 0?
- or step size < 0?
- or step size does not divide stop num?