Loading…
Loading…
In this lesson, students will explore the use of functions in Python. Students will use the function to create a computational model on the ball selection probability. Students will then create a ‘ball drawing’ function and define how it should work to simulate the ball selection. Students also need to recall and utilize what they have learned about lists to store and modify data.
In this lesson, students will explore the use of functions in Python. Students will use the function to create a computational model on the ball selection probability. Students will then create a ‘ball drawing’ function and define how it should work to simulate the ball selection. Students also need to recall and utilize what they have learned about lists to store and modify data.
Recognize 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.
Welcome to this Python Coding lesson! Before you begin, take a few moments to let us know your thoughts or feedback on how we can improve this lesson in order to better enhance the learning experience that is delivered in your classroom!
Click here or follow the form below to complete the feedback survey once you've completed this lesson. Thank you!
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 utilize what they have learnt about lists to store and modify data.
Students should have a laptop or device with mBlock 5 installed (desktop version or cloud-based version) and mBlock Python editor (mLink) installed.
Worksheet: Ball Selection
Example Program: Ball Selection
1. 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.
2. 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.
3. Definitions:
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 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.
4. Have students fill out the ‘What I Know’ column of the K-W-L chart before the class.

1. When you open the editor for the first time you will see these explanations mapping the interface. Encourage students to thoroughly read through it. Below are the screen captures if you ever need to reference them again.
Figure 1: To connect your CyperPi

Figure 2: Creating Projects and Project files (see How to Create, Open, Import, or Export Project Files)

Figure 3: Editing Area

Figure 4: Console Commands to run code and more

Figure 5: Terminal (Console) to display output from Editing Area

Figure 6: Libraries containing example program. Feel free to explore these at your leisure

Figure 7: Click "Tutorials" to view these helpful instructions anytime

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.
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:
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.
1. Have students read "Activity 1" in the example program.

2. 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?
3. Ask students to explain the program and draw a flowchart.

4. 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.
5. 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.

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 ‘random.choice()’ 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.
Explain how to place the ‘ball’ into the list ‘balls’: There is a new method used in the example program: the ‘balls.append(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:

Ask students to observe the output in the console and figure out how an item is added into a list.
6. 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’.
Ask students to explain the meaning of the expressions ‘balls[0] == balls[1]’ and ‘balls[1] == balls[2]’ in their own words.
7. 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:
n = int(input(“The number of times to throw up a coin: ”))
for i in range(0, n):
or
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 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.
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.
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.

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?
Are they independent events or dependent events? Why?

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?

Have students fill out the K-W-L chart
Remind students to always comment their code, regardless of the simplicity

It is common practice that functions represent actions
These actions should complete a specific task and shouldn't be large in size
Go back to previous lessons and break down the programs into functions that complete specific tasks
1. Recognize the syntax and features of a function in Python, including the keyword, the rule of indentation, the method to call and reuse the function.
2. Write and execute algorithms that define a function to store a set of instructions or procedures.
A. Programming Concepts and Skills
A1. Data types and Expressions
A1.1 use constants and variables, including integers, floating points, strings, and Boolean values, correctly in computer programs;
A1.3 use assignment statements correctly with both arithmetic and string expressions in computer programs;
A1.4 demonstrate the ability to use Boolean operators (e.g., AND, OR, NOT), comparison operators (i.e., equal to, not equal to, greater than, less than, greater than or equal to, less than or equal to), arithmetic operators (e.g., addition, subtraction, multiplication, division, exponentiation, parentheses), and order of operations correctly in computer programs;
A1.5 describe the structure of one-dimensional arrays and related concepts, including elements, indexes, and bounds;
A1.6 write programs that declare, initialize, modify, and access one-dimensional arrays.
A2. Control Structures and Simple Algorithms
A2.1 write programs that incorporate user input, processing, and screen output;
A2.2 use sequence, selection, and repetition control structures to create programming solutions;
A2.3 write algorithms with nested structures (e.g., to count elements in an array, calculate a total, find highest or lowest value, or perform a linear search).
A3. Subprograms
A3.1 demonstrate the ability to use existing sub- programs (e.g., random number generator, substring, absolute value) within computer programs;
A3.2 write subprograms (e.g., functions, procedures) that use parameter passing and appropriate variable scope (e.g., local, global), to perform tasks within programs.
A4. Code Maintenance
A4.1 demonstrate the ability to identify and correct syntax, logic, and run-time errors in computer programs;
A4.2 use workplace and professional conventions (e.g., naming, indenting, commenting) correctly to write programs and internal documentation;
A4.3 demonstrate the ability to interpret error messages displayed by programming tools (e.g., compiler, debugging tool), at different times during the software development process (e.g., writing, compilation, testing);
A4.4 use a tracing technique to understand pro- gram flow and to identify and correct logic and run-time errors in computer programs;
A4.5 demonstrates the ability to validate a program using a full range of test cases.
B. Software Development
B1. Problem-solving Strategies
B1.2 demonstrate the ability to solve problems independently and as part of a team;
B2. Designing Software Solutions
B2.1 design programs from a program template or skeleton (e.g., teacher-supplied skeleton, Help facility code snippet);
B2.2 use appropriate vocabulary and mode of expression (i.e., written, oral, diagrammatic) to describe alternative program designs, and to explain the structure of a program;
B2.4 represent the structure and components of a program using industry-standard program- ming tools (e.g., structure chart, flow chart, UML [Unified Modelling Language], data flow diagram, pseudocode);
B2.5 design user-friendly software interfaces (e.g., prompts, messages, screens, forms).
B3. Designing Algorithms
B3.1 design simple algorithms (e.g., add data to a sorted array, delete a datum from the middle of an array) according to specifications;
B3.2 solve common problems (e.g., calculation of hypotenuse, determination of primes, calculation of area and circumference) by applying mathematical equations or formulas in an algorithm;
A. Programming Concepts and Skills
A1. Data Types and Expressions
A1.1 use constants and variables, including integers, floating points, strings, and Boolean values, correctly in computer programs;
A1.3 use assignment statements correctly with both arithmetic and string expressions in computer programs (e.g., numStudents = 4 + 2, name = “Devi”);
A1.4 use Boolean operators (e.g., AND, OR, NOT), comparison operators (i.e., equal to, not equal to, greater than, less than, greater than or equal to, less than or equal to), arithmetic operators (e.g., addition, subtraction, multiplication, divi- sion, exponentiation, parentheses), and order of operations correctly.
A2. Control Structures and Simple Algorithms
A2.1 write programs that incorporate user input, processing, and screen output;
A2.2 use sequence, selection, and repetition control structures to create programming solutions;
A2.3 Demonstrate the ability to write algorithms with nested structures.
A3. Code Maintenance
A3.2 demonstrate the ability to correct syntax, logic, and run-time errors in computer programs;
A3.3 use workplace and professional conventions (e.g., naming, indenting, commenting) correctly to write programs and internal documentation;
A3.4 demonstrate the ability to interpret error messages displayed by programming tools (e.g., compiler, debugging tool), at different times during the software development process (e.g., writing, compilation, testing);
A3.5 demonstrate the ability to validate a program using test cases.
B. Software Development
B1. Problem-solving Strategies
B1.1 use various problem-solving strategies (e.g., divide and conquer, working backwards, process analysis, examples, extreme cases, tables and charts, trial and error) to solve program- ming problems;
B2. Designing Software Solutions
B2.1 design a simple program from a program template or skeleton (e.g., teacher-supplied skeleton, Help facility code snippet);
B2.2 use appropriate vocabulary and mode of expression (i.e., written, oral, diagrammatic) to describe alternative program designs and to explain the structure of a program;
B2.3 write subprograms (e.g., functions, procedures) that perform one well-defined task and use parameter passing and appropriate variable scope (e.g., local, global);
B2.4 use industry-standard programming tools (e.g., structure chart, flow chart, UML [Unified Modelling Language], data flow diagram, pseudo- code) to represent the structure and components of a computer program;
B2.5 design user-friendly software interfaces (e.g., prompts, messages, screens, forms).
B3. Designing Simple Algorithms
B3.1 use simple algorithms (e.g., validate entered data, count, accumulate, use random numbers) to design a program according to specifications;
B3.2 solve problems (e.g., calculation of gross pay; fuel consumption on a car trip; average of students’ marks; temperature at a given altitude, using the environmental lapse rate) by applying mathematical equations or formulas in an algorithm;