You are on page 1of 23

[Header

Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Condition-controlled iterations
import random

# Subroutine to roll a dice until a 6 is rolled


def RollSix():
Roll = 0
NumberRolls = 0
while Roll !=6:
Roll = random.randint(1,6)
NumberRolls = NumberRolls + 1
return NumberRolls

# Main program
Result = RollSix()
print("It took {} rolls of a dice to roll a 6.".format(Result))

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program simulates rolling a dice until a six is thrown.

Understand how the code works: • It is not possible to know how many rolls will be required before a six is thrown, so you
cannot use a for loop in this program.
# Condition-controlled iterations
• A while loop will keep executing code the tabulated code until a condition is met.
import random

# Subroutine to roll a dice until a 6 is rolled


def RollSix():
Roll = 0
• .This means repeat the code while the roll is not 6.
NumberRolls = 0
while Roll !=6:
Roll = random.randint(1,6)
NumberRolls = NumberRolls + 1 • A common mistake is to put the code that changes the variable required for the condition
return NumberRolls outside of the loop.
A statement that changes the value of Roll must be inside the loop to avoid looping indefinitely.
# Main program
Result = RollSix()
print("It took {} rolls of a dice to roll a 6.".format(Result))

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Condition-controlled iterations

# Subroutine to use trial and error to calculate LCD


def LCD(Number1, Number2):
Counter = 1
while Counter % Number1 != 0 or Counter % Number2 !=0:
Counter = Counter + 1
return Counter

# Main program
Number1 = 20
Number2 = 7
Result = LCD(Number1, Number2)
print("The LCD of {} and {} is {}".format(Number1, Number2, Result))

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program calculates the least common denominator of two numbers.

Understand how the code works:


# Condition-controlled iterations
2. Counter will become the lowest common denominator of the two numbers at the
# Subroutine to use trial and error to calculate LCD
end of the function.
def LCD(Number1, Number2):
It is initialised to 1 as the starting point for the algorithm..
Counter = 1
while Counter % Number1 != 0 or Counter % Number2 !=0:
Counter = Counter + 1
return Counter 3. While the counter divided by either number is not a whole number, the common
denominator has not been found. The use of modulus here provides an easy way to
# Main program determine whether Counter divided by Number is an integer.
Number1 = 20
Number2 = 7 Note how the while can include more than one condition.
Result = LCD(Number1, Number2)
print("The LCD of {} and {} is {}".format(Number1, Number2, Result))

1. The program starts here by assigning two variables and calling the LCD
function with those parameters. The numbers are stored in variables so
that they can be used in the output statement later.
START
HERE

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Condition-controlled iterations

# Subroutine to show spread of a virus


def ModelVirus(Day, CurrentCases, R, Target):
PopulationInfected = CurrentCases
while PopulationInfected < Target:
PopulationInfected = int(CurrentCases * (2.718 ** (R * Day)))
print("People infected on day {}: {}".format(Day, PopulationInfected))
Day = Day + 1

# Main program
ModelVirus(1,1,1.2,10000)

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program models the rate of infection of a virus.

Understand how the code works:


# Condition-controlled iterations
• The code is repeated while PopulationInfected is less than
# Subroutine to show spread of a virus Target. This prevents an infinite loop and also the
def ModelVirus(Day, CurrentCases, R, Target): numbers becoming so large the computer cannot store
PopulationInfected = CurrentCases them.
while PopulationInfected < Target:
PopulationInfected = int(CurrentCases * (2.718 ** (R * Day)))
print("People infected on day {}: {}".format(Day, PopulationInfected))
Day = Day + 1
• Casting to an integer ensures that the result of a
# Main program
calculation is a whole number. In this model you can’t
ModelVirus(1,1,1.2,10000)
have part of a person, so integers need to be used when
storing the number of people.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Condition-controlled iterations

# Infinite loop
def ToInfinity():
while True:
print("To infinity and beyond...")

# Main program
ToInfinity()

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program demonstrates an infinity loop.

Understand how the code works:


# Condition-controlled iterations

# Infinite loop • while (True) achieves an infinite loop


def ToInfinity(): because True will always be True.
while True:
print("To infinity and beyond...")

# Main program
ToInfinity()
• Sometimes it is useful for a program to never end, for example software in embedded systems
which constantly check for inputs.
• In Windows you can close a program by clicking on the cross in the top right corner of the
application window. On iOS you can terminate applications by swiping up. Therefore an infinite
loop to continue running a program until it is terminated by the operating system may be useful.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Learning points from this objective:
• When it is not known in advance how many times code needs to be repeated, a condition-controlled iteration is used.
• Code in an iteration is tabulated.
• It is good practice to comment code before an iteration to explain what is happening.
• Condition-controlled iterations can also be used as an alternative to counter-controlled iterations. Some languages only support condition-controlled iterations.
However, it is considered good practice to use the correct type of iteration if the language supports it.
• Condition controlled iterations are useful when you want to validate data entry by only continuing to the next statements once the data input is correct.
You will learn about this in the next objective.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Program comprehension: ITEM Identify the line number where casting is used.

1. def D2(Y):
2. Z = int(Y)
3. Count = 0 What data type is returned from function D2?
4. while Z > 1:
5. Z = Z / 2
6. Count = Count + 1
7. return Count
Identify the condition in the program.
8. X = "8"
9. print(D2(X))

PURPOSE What is the value of Z at line 3?

What does this program output to the screen?

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Program comprehension: REASON Why is casting necessary?

1. def D2(Y):
2. Z = int(Y)
3. Count = 0 Why is a while loop needed instead of a for loop in this
program?
4. while Z > 1:
5. Z = Z / 2
6. Count = Count + 1
7. return Count

8. X = "8"
9. print(D2(X))

How is the execution time of the algorithm affected if X is a


RELATION higher number?

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Keywords introduced in this objective:
while X > 0: Executes the tabulated code underneath the while statement until the condition is met (X > 0).
commands… Tabulated code is not executed at all if the condition is false.
The condition can include multiple conditions.
You can use brackets around each condition if necessary.
The condition can include operators <, <=, ==, >=, >, !=, and, or
The condition always returns True or False.
While True: An infinite loop.
commands…

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
# Compound interest problem

Compound interest problem:


# Subroutine to output the interest growth on a balance
1 point.
Write a program that shows how compound interest
grows in a savings bank account. Year = 1

The subroutine takes three parameters, the current


balance, the interest rate (0.04 would be 4%) and the #Iterate until the balance matches the target
desired balance to reach. balance
The program should output the new balance each year def Compound(Balance, InterestRate, TargetBalance):
until the desired balance is reached.
Interest is added to the balance each year. E.g.
Interest = Balance * InterestRate
£100 starting balance – 4% interest rate (0.04)
Year 1: New balance = 100 + (100*0.04) = £104
while Balance < TargetBalance:
Year 2: New balance = 104 + (104*0.04) = £108.16
Year 3: New balance = 108.16 + (108.16*0.04) = £112.49
# Main program

print("Year {}: New balance = £


{:.2f}".format(Year, Balance))

Year = Year + 1

To help you get started, Balance = Balance + Interest


here is all the code you
need with the
statements jumbled up.
Compound(100, 0.04, 200) PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Car value problem:
1 point.
Write a program that illustrates the depreciation of the value of a car. The program takes three parameters, the year, the value of the car
and the minimum resale value. The car depreciates by 30% in the first and second year, and 20% in each subsequent year. The program
should output the values from the model until the resale value is reached. E.g.
Car is bought for £12500. Minimum resale value is £6000.
2020: £12500
2021: £8750
2022: £6125
Part exchange in 2022.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Discount counter problem:
1 point.
An electronic advertising board illustrates a sale at 60% off. To make this more eye-catching, the number shown starts at 10 and increases
by a random amount until 60 is reached. Write an algorithm that will achieve this. E.g.
10% off.
24% off.
48% off.
60% off.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Lottery problem:
2 points.
The top prize in a lottery is won by matching three numbers between 1 and 30 to three random numbers drawn in the same order. When
a ball is drawn it is put back into the machine before another ball is drawn. There are always 30 balls in the machine before a ball is drawn
and a player may choose the same ball more than once. A draw takes place once a week. Write a function that takes three numbers as
parameters, draws three random numbers between 1 and 30 and returns the number of weeks it took to win the jackpot. E.g.
Numbers chosen: 17, 12, 25 must match: ball one is 17, ball two is 12, ball three is 25.

Cashpoint problem:
2 points.
An automated teller machine (ATM) or cashpoint allows customers to withdraw money in £20, £10 and £5 notes. The machine always
dispenses the minimum number of notes. Write a program that would control the actuators dispensing notes from a withdrawal request.
The necessary function takes the amount to withdraw as a parameter. A typical output is:
Withdraw: £115.
Dispense £20.
Dispense £20.
Dispense £20.
Dispense £20.
Dispense £20.
Dispense £10.
Dispense £5.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Square root problem:
2 points.
Write a function called SqRoot that calculates the square root of a number, X using Newton’s method.
Root = X at the start of the algorithm.
Root is repeatedly recalculated as 0.5*(Root+(X/Root) until the value of Root does not change. E.g. the square root of 64 can be
calculated in the sequence of steps:
64
32.5
17.234615384615385
10.474036101145005
8.292191785986859
8.005147977880979
8.000001655289593
8.00000000000017
8.0
8.0 – This value equals the previous value of Root.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Denary to binary problem:
3 points.
Write a function that converts a denary number into a binary number using the repeated division by two algorithm:
1. The number to be converted is divided by two.
2. The remainder from the division is the next binary digit. Digits are added to the front of the sequence.
3. The result is truncated so that the input to the next division by two is always an integer.
4. The algorithm continues until the result is 0.
E.g.

Denary Divide by 2 Remainder Binary

26 13 0 0

13 6 1 10

6 3 0 010

3 1 1 1010

1 0 1 11010

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Happy numbers problem:
3 points.
Write a function to return whether a number is happy or sad. A happy number is a number defined by the following process: Starting
with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number either
equals 1, or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers,
while those that do not end in 1 are sad numbers. When the algorithm ends in a cycle of repeating numbers, this cycle always includes
the number 4.
E.g. 19 is a happy number:

First digit Second digit Third digit Calculation Result

1 9 12 + 9 2 82

8 2 82 + 2 2 68

6 8 62 + 8 2 100

1 0 0 12 + 0 2 + 02 1

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Predator-prey problem:
3 points.
The relationship between the number of predators and the number of prey can be modelled using the Lotka-Volterra equations. Put
simply, as the population of prey increase, so too does the population of predators. As the number of predators increases, the number of
prey decreases. This results in a reduction of available food and the number of predators decreases. In the natural world, given no other
environmental factors affect the model, an equilibrium is reached with numbers rising and falling in a cycle.
The Lotka-Volterra equations use six parameters: Prey, Predators and values A, B, C and D that represent the relationship between the
two groups of animals. In addition, the exponential constant (E) is a useful addition to the equation.
Assume the following values:
Prey Predators A B C D E

30 5 0.8 0.5 0.1 0.3 2.718

A generation is one iteration of the algorithm.


In one generation the prey growth rate is: E to the power of (A-(C*Predators))
The new number of prey for the next generation is prey*prey growth rate.
In the same generation, the predator growth rate is: E to the power of ((D*C*new number of prey)-B)
The new number of predators for the next generation is predators*predator growth rate.
Prey and predators must always be integers.
Write a function that outputs the generation, prey and predators for a given number of generations while neither the prey, nor predator
numbers are less than two.
As an interesting additional exercise you could plot the values your algorithm gives you in a chart in a spreadsheet to test the model.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

MAKE
Predator-prey problem:
Use this table of test data to check your algorithm is working.

Generation Prey Prey growth Total prey Predators Predator growth Total predators

1 30 1.35 40 5 2.04 10
2 40 0.80 32 10 1.60 16
3 32 0.43 14 16 0.92 15
4 14 0.49 7 15 0.75 11
5 7 0.72 5 11 0.70 8
6 5 1.01 5 8 0.70 6
7 5 1.27 6 6 0.73 4
8 6 1.48 9 4 0.80 3
9 9 1.60 15 3 0.95 3
10 15 1.63 24 3 1.26 4

If your numbers are different for total prey or total predators it could be because you are casting instead of formatting the totals, or
perhaps you are incrementing the generation at the wrong time.
With these input values the model should establish a cyclical steady state.

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

EVALUATE
Test tables:
Problem:

Parameter 1 Parameter 2 Expected output Pass/Fail Test

Problem:

Parameter 1 Parameter 2 Expected output Pass/Fail Test

PYTHON T I M E
[Header
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave

EVALUATE
Review your solutions:
Did you: Self-assess: Yes/No

Complete all the requirements for the problems you solved?

Start your programs with a comment to describe what they do?

Use a subroutine for the main algorithm in your code?

Use a comment to describe what the subroutine does?

Use a comment after each program branch to explain the purpose of the section?

Use a comment before each iteration to explain the purpose of the loop?

Use variable names that describe the data they hold?

Test your programs against different types of data to check they work?

PYTHON T I M E

You might also like