Python - Objective 06 Learn How To Use Condition-Controlled Iterations Workbook
Python - Objective 06 Learn How To Use Condition-Controlled Iterations Workbook
Learn text]
how to use condition-controlled iterations Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Condition-controlled iterations
import random
# 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
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
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
# 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.
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
# 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
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
# 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))
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))
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
Year = Year + 1
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.
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:
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
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:
Problem:
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
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?
Test your programs against different types of data to check they work?
PYTHON T I M E