Lesson 10 Draw the Balls
Category: Python Level: Introductory Time Frame: 45 minutes
Core Subject Area: Computing Supplementary Subject Area: Mathematics
Ages: 11~14 years old Year Groups: Key Stage 3 (UK) / Grades 6–8 (US)
Overview
This lesson will introduce the use of functions in Python. Students will use the function to
create a computational model on the ball selection probability. Students need to create a
‘ball drawing’ function and define how it should work to simulate the ball selection.
Students also need to recall and utilise what they have learnt about lists to store and
modify data.
Key Focus
Use of functions
Use of lists
Intended Learning Outcomes
By the end of this lesson, students will be able to:
Recognise the syntax and features of a function in Python, including the keyword, the
rule of indentation, the method to call and reuse the function
Write and execute algorithms that define a function to store a set of instructions or
procedures
Page 1
Content Standards
(UK)
National Curriculum in England – Computing Programmes of Study: Key Stage 3
Design, use and evaluate computational abstractions that model the state and
behaviour of real-world problems and physical systems
Use two or more programming languages, at least one of which is textual, to solve a
variety of computational problems
National Curriculum in England – Mathematics Programmes of Study: Key Stage 3
Develop their mathematical knowledge, in part through solving problems and
evaluating the outcomes, including multi-step problems
Record, describe and analyse the frequency of outcomes of simple probability
experiments involving randomness, fairness, equally and unequally likely outcomes,
using appropriate language and the 0-1 probability scale
Understand that the probabilities of all possible outcomes sum to 1
Page 2
(US)
CSTA K-12 Computer Science Standards: Grades 6~8
2-AP-11: Create clearly named variables that represent different data types and
perform operations on their values.
2-AP-12: Design and iteratively develop programs that combine control structures,
including nested loops and compound conditionals.
Common Core State Standards Mathematics Standards: Grades 6~8
[Link].C.5: Understand that the probability of a chance event is
a number between 0 and 1 that expresses the likelihood of the event occurring. Larger
numbers indicate greater likelihood. A probability near 0 indicates an unlikely event, a
probability around 1/2 indicates an event that is neither unlikely nor likely, and a
probability near 1 indicates a likely event.
[Link].C.6: Approximate the probability of a chance event by
collecting data on the chance process that produces it and observing its long-run
relative frequency, and predict the approximate relative frequency given the
probability. For example, when rolling a number cube 600 times, predict that a 3 or 6
would be rolled roughly 200 times, but probably not exactly 200 times.
[Link].C.7: Develop a probability model and use it to find
probabilities of events. Compare probabilities from a model to observed frequencies; if
the agreement is not good, explain possible sources of the discrepancy.
Page 3
Preparation
For the teacher:
A laptop or desktop with mBlock Python editor installed
(Available from [Link]
Lesson plan
Worksheet
For students:
Laptops or desktops with mBlock Python editor installed
(Available from [Link]
Worksheets
Page 4
Example Program
1. import random
2.
3.
4. # Define a function:
5. def drawballs(n):
6. p = 0
7. for i in range(n):
8. bag = ["y", "g", "g", "r", "r", "r", "b", "b", "b", "b"]
9. balls = []
10. draws = 3
11. for j in range(draws):
12. ball = [Link](bag)
13. [Link](ball)
14. print(balls)
15. if balls[0] == balls[1] and balls[1] == balls[2]:
16. p += 1
17.
18. chance = round(p/n * 100, 2)
19. print("The probability of all the same colour is", chance, "%")
20.
21.
22. # Call the function:
23. drawballs(1000)
Note: Familiarise yourself with the key points that you are going to teach in this lesson::
The concept of the function
The keyword used to define a function
How to call a function and modify the parameter of the function
Page 5
Task for Enquiry – Probability
What are independent and dependent events?
An event can be independent or dependent. Independent events do not affect one
another. For example, whether you get heads or tails while tossing a coin in the first
trial does not affect the outcome of the second trial. If you get Number 6 in the first
round while rolling a dice, you can still roll this number in the next round.
Dependent events, however, are affected by other events. For example, there are six
balls in a bag: two red balls, two blue balls, and two green balls. One ball is picked out,
and not replaced, and then another ball is picked out. The probability of getting a green
ball can be affected by the previous selection. Probabilities of dependent events are
conditional probabilities.
Why does frequency matter?
Probability problems usually address the frequency of outcomes of events. Relative
frequency is an estimate of probability and is calculated based on repeated trials of an
experiment. The number of times of tossing a coin or rolling a dice affects the
frequency of outcomes. If your objective is to investigate a combined event that
contains more than one outcome, you can find that the amount of trials can affect the
probability of certain events.
Glossary
Event: A set of outcomes of an experiment that has some properties for investigation.
Experiment: An occurrence with an uncertain outcome
Frequency: How many times an outcome occurs.
Outcome: The result of an experiment.
Probability: The extent to which something is likely to happen. Probabilities are written
Page 6
as fractions, decimals, or percentages with values between 0 and 1.
Probability Scale: The extent that starts at the extreme of ‘impossible’ and ends at the
extreme of ‘certain’.
Sample Space: The set of all possible outcomes for the experiment.
Page 7
Pre-assessment
Have students fill out the ‘What I Know’ column of the K-W-L chart before the class.
What I Know What I Wonder What I Learnt
Import random
Loops
Conditionals nested inside
the loop
Lists
Page 8
Procedures
Section 1 Introduction: Independent and Dependent Events (8 minutes)
Step 1.1 Introduce the concept of independent events.
Recall the two dice rolling probability problem: In the previous learning activity,
we experiment and investigate the probability of the sum of the dice numbers.
When we roll two dice, the probability of getting Number 1 on the second dice
is the same as the probability of getting Number 1 on the first dice – both are
1/6. Therefore, the probability of getting the sum of 2 is 1/36.
Explain the concept of independent events: The probability of the number that
occurs in the first dice does not affect the probability of the number that
occurs in the second dice. These two events are independent. The outcomes of
rolling two dice are independent events.
Ask students to recall the coin tossing probability problem in Lesson 7. Have
them think about whether the outcomes of tossing a coin are independent or
not and give their reasons.
Explain: The outcomes of tossing a coin are independent events because the
result of the first toss does not affect the second case. The probability of
getting a head (or getting a tail) is 1/2 for each trial.
Step 1.2 Introduce the concept of dependent events.
Explain: However, if the first occurrence can affect the probability of the
second result, we say they are dependent events. A dependent event is an
outcome or occurrence that relies on another outcome or occurrence to happen
first. For example, in Lesson 8 ‘Guess the Number’, the first guess of the
number may affect the next guess of the number, if the first try is incorrect.
Have students think about the probability problem below:
Page 9
There are 10 coloured balls in a bag: 1 is yellow, 2 are green, 3 are red, and the
rest 4 are blue. You will pick 3 balls from the bag each time and repeat it 1, 000
times. What is the probability of getting the 3 balls of the same colour?
Ask students to think about how the outcomes may affect each other, and the
probability of drawing the balls.
Page 10
Section 2 Predict (5 minutes)
Step 2.1 Distribute the example program file to the class. Have students read the code
and discuss what they think it will do.
Say: This computational model is to simulate the above balls drawing
probability problem. Observe the programming script to figure out how it
works.
1. import random
2.
3.
4. def drawballs(n):
5. p = 0
6. for i in range(n):
7. bag = ["y", "g", "g", "r", "r", "r", "b", "b", "b", "b"]
8. balls = []
9. draws = 3
10. for j in range(draws):
11. ball = [Link](bag)
12. [Link](ball)
13. print(balls)
14. if balls[0] == balls[1] and balls[1] == balls[2]:
15. p += 1
16.
17. chance = round(p/n * 100, 2)
18. print("The probability of all the same colour is", chance, "%")
19.
20.
21. drawballs(1000)
Page 11
Ask students to think about the questions below:
Identify the line of code that represents the collection of coloured balls.
How does the simulation program draw 3 balls from the bag?
How does the program modify the item of a list?
How to check whether the selected balls have the same colour or not?
How to repeat the trials of drawing balls in the program?
Page 12
Section 3 Run (2 minutes)
Step 3.1 Ask students to run the example program and check against their predictions.
Instruct students to think about the above questions while running the
program.
Page 13
Section 4 Investigate (18 minutes)
Step 4.1 Point out the lists created and used in the example program.
Say: There are two lists: ‘bag’ and ‘balls’. The ‘bag’ list contains 10 items which
represent the 10 coloured balls in this experiment. The ‘balls’ list is created as
an empty list. It is then assigned values that represent the 3 selected balls.
bag = [“y”, “g”, “g”, “r”, “r”, “r”, “b”, “b”, “b”, “b”]
balls = []
Remind students that lists can contain both text and numeric data. In this
example, the lists are used to store strings.
Step 4.2 Explain how the program draws balls.
Ask students to recall what they have learnt and to identify the control
structure used to execute the action of picking balls.
1. import random
2.
3. for i in range(10):
4. bag = ["y", "g", "g", "r", "r", "r", "b", "b", "b", "b"]
5. balls = []
6. draws = 3
7.
8. for j in range(draws):
9. [Link]([Link](bag))
10. print(balls)
Explain: To simulate ball selection, the example program uses the for loop to
design the algorithm. First, it creates a variable named ‘draws’ and assigns the
value of ‘3’ to it – which means, to select 3 balls from the bag.
Then, it uses the ‘[Link]()’ to pick 3 coloured balls at random and store
the value of the ‘ball’ in the list ‘balls’.
Give students some time to think about the use of the line of code before you
explain the new function of the list.
Page 14
Explain how to place the ‘ball’ into the list ‘balls’: There is a new method used in
the example program: the ‘[Link](ball)’. The ‘append’ method can add an
item to the end of a list. If we have a look at the console, we can find that the
list ‘balls’ has new items after executing the second for loop (i.e., ‘for i in
range(draw):’).
Have students to rewrite the above script in the Python editor and modify the
parameter, for example:
1. import random
2.
3. for i in range(10):
4. bag = ["y", "g", "g", "r", "r", "r", "b", "b", "b", "b"]
5. balls = []
6.
7. for j in range(5):
8. [Link]([Link](bag))
9. print(balls)
Ask students to observe the output in the console and figure out how an item is
added into a list.
Step 4.3 Explain how the program checks whether the selected balls have the same
colour or not.
Point out the script below:
if balls[0] == ball[1] and balls[1] == balls[2]:
p += 1
Ask students to recall what they have learnt and explain the syntax ‘balls[0]’.
Explain: The ‘balls[0]’ (or ‘balls[1]’ or ‘balls[2]’) is to read an item at a certain
position in the list. The square bracket ‘[]’ is the index operator. The expression
‘balls[0]’ is to return the value of the item at the index position of ‘0’ in the list
‘balls’.
Remind students that the index of a list starts from ‘0’.
Page 15
Ask students to explain the meaning of the expressions ‘balls[0] == balls[1]’ and
‘balls[1] == balls[2]’ in their own words.
Step 4.4 Explain the use of functions.
Ask: In the previous learning activities, how do we program the iteration of the
trials?
Possible Answer: The expressions below are used:
Example 10-1 (a)
n = int(input(“The number of times to throw up a coin: ”))
for i in range(0, n):
Example 10-1 (b)
n = int(input(“The number of times to roll 2 dice: ”))
t = 0
while t < n:
Instruct students to identify the lines of code below in the example program:
Line 4: def drawballs(n):
Line 6: for i in range(n):
Line 10: for j in range(draws):
Line 21: drawballs(1000)
Say: In the example program, if we change the parameter of the code in Line
20, we can modify the number of times of iteration. The ‘drawballs()’ is a
function in Python that contains a set of instructions.
Explain: A function is a group of related statements that performs a specific
task. To create a function, we need to use the keyword ‘def’ as the function
header.
To define the function, we need to use the indentation to indicate a group of
code belongs to the function. In the example program, for instance, the
Page 16
statements from Line 4 to Line 14 belong to the function ‘drawballs’. These
statements define how the function ‘drawballs’ works.
Briefly mention some of the advantages of using functions.
Say: Functions help reduce duplication of code. For example, if we want to
know the probability of getting the balls of the same colour in 100 trials, in
1,000 trials, as well as in 10,000 trials, we can use the ‘drawballs()’ function to
calculate the probabilities at the same time.
Example 10-2
drawballs(100)
drawballs(1000)
drawballs(10000)
Say: We can reuse the code by calling the function when needed without
rewriting the same set of instructions.
Page 17
Section 5 Modify and Make (10 minutes)
Step 5.1 Instruct students working individually to modify the example program by
completing the tasks below:
Task 1: Add two lines of code to call the ‘drawballs()’ function. One is to repeat
the experiment in 100 trials and the other is in 10,000 trials. Compare the
probabilities.
Task 2: Modify the function to solve the problem below:
Pick 4 balls from the bag each time. What is the probability of getting 4 blue
balls and the probability of getting the yellow ball among the 4 selected balls?
Tip: A syntax that may be used is ‘item in list’. It returns ‘True’ if the target item
exists in the list.
Page 18
Example – Task 2
1. import random
2.
3.
4. def drawballs(n):
5. p_a = 0
6. p_b = 0
7. for i in range(n):
8. bag = ["y", "g", "g", "r", "r", "r", "b", "b", "b", "b"]
9. balls = []
10. draws = 4
11. for j in range(draws):
12. ball = [Link](bag)
13. [Link](ball)
14. if balls[0] == balls[1] == balls[2] == balls[3]:
15. p_a += 1
16. elif "y" in balls:
17. p_b += 1
18.
19. chance_a = round(p_a/n * 100, 2)
20. chance_b = round(p_b/n * 100, 2)
21. print("The probability of 4 blue balls is", chance_a, "%")
22. print("The probability of getting the yellow ball is", chance_b, "%")
23.
24.
25. print("100 Trials:")
26. drawballs(100)
27. print("1,000 Trials: ")
28. drawballs(1000)
29. print("10,000 Trials: ")
30. drawballs(10000)
Task 3: Modify the program to answer the question below:
There are 2 bags. In one bag, there are 3 white balls and 2 blue balls; in another
bag, there are 2 red balls, 2 green balls, and only 1 blue ball.
You will pick one ball from each bag and then put it back each time. Repeat the
experiment 1, 000 times. What is the probability of getting both blue balls?
Page 19
Are they independent events or dependent events? Why?
Example – Task 3
1. import random
2.
3.
4. def drawballs(n):
5. p = 0
6. for i in range(n):
7. bag_a = ["w", "w", "w", "b", "b"]
8. bag_b = ["r", "r", "g", "g", "b"]
9. balls = []
10. ball_1 = [Link](bag_a)
11. [Link](ball_1)
12. ball_2 = [Link](bag_b)
13. [Link](ball_2)
14. print(balls)
15. if balls[0] == balls[1]:
16. p += 1
17.
18. chance = round(p/n * 100, 2)
19. print("The probability of getting both blue balls is", chance, "%")
20.
21.
22. drawballs(1000)
Task 4: Refer to Lesson 9 and create a ‘rolldice’ function. The program should
solve the problems as follows:
Roll 2 dice 1,000 times and calculate the sum of the dice numbers.
(a) What is the probability that the two dice numbers are the same?
(b) What is the probability of the sum being greater than 7?
(c) What are the probabilities of the sum being odd or the sum being even?
Page 20
Example – Task 4
1. import random
2.
3.
4. def rolldice(n):
5. p_same = 0
6. p_seven = 0
7. p_odd = 0
8. p_even = 0
9. for i in range(n):
10. dice_x = [Link](1, 6)
11. dice_y = [Link](1, 6)
12. result = dice_x + dice_y
13. print("(", dice_x, ",", dice_y, ")")
14. if dice_x == dice_y:
15. p_same += 1
16. if result > 7:
17. p_seven += 1
18. elif result % 2 == 0:
19. p_even += 1
20. else:
21. p_odd += 1
22.
23. chance_same = round(p_same/n * 100, 2)
24. print("Dice numbers are same:", chance_same, "%")
25. chance_seven = round(p_seven/n * 100, 2)
26. print("Sum is greater than 7:", chance_seven, "%")
27. chance_odd = round(p_odd/n * 100, 2)
28. print("Sum is odd:", chance_odd, "%")
29. chance_even = round(p_even/n * 100, 2)
30. print("Sum is even:", chance_even, "%")
31.
32.
33. rolldice(1000)
Page 21
Section 6 Recap (2 minutes)
Step 6.1 Summarise this lesson.
Have students fill out the K-W-L chart.
What I Know What I Wonder What I Learnt
Import random What is a function? Functions
Loops How to create a function?
Conditionals nested inside
the loop
Lists
Page 22