Computing E-Notes
Computing E-Notes
Computing E-Notes
Syllabus 1.0
Learning Material
Provided by:
ECDL Malta
© 2017 Page i
Copyright ECDL Foundation 2015 - 2019. All rights reserved. Reproducing, repurposing, or distributing this courseware without the
permission of ECDL Foundation is prohibited.
ECDL Foundation, ECDL Europe, ECDL and related logos are registered business names and/or trademarks of ECDL Foundation.
This courseware may be used to assist candidates to prepare for the ECDL Foundation Certification Programme as titled on the
courseware. ECDL Foundation does not warrant that the use of this courseware publication will ensure passing of the tests for that ECDL
Foundation Certification Programme.
The material contained in this courseware does not guarantee that candidates will pass the test for the ECDL Foundation Certification
Programme. Any and all assessment items and / or performance-based exercises contained in this courseware relate solely to this
publication and do not constitute or imply certification by ECDL Foundation in respect of the ECDL Foundation Certification Programme or
any other ECDL Foundation test. This material does not constitute certification and does not lead to certification through any other
process than official ECDL Foundation certification testing.
Candidates using this courseware must be registered with the National Operator before undertaking a test for an ECDL Foundation
Certification Programme. Without a valid registration, the test(s) cannot be undertaken and no certificate, nor any other form of
recognition, can be given to a candidate. Registration should be undertaken at an Approved Test Centre.
Python is a registered trademark of the Python Software Foundation. Python and it standard libraries are distributed under the Python
License. Details are correct as of December 2016. Online tools and resources are subject to frequent update and change.
With the increased use of computers in all areas of life, there is a growing interest in
learning about the fundamentals of computing, including the ability to use computational
thinking and coding to create computer programs.
The ECDL Computing module sets out the skills and competences relating to computational
thinking and coding and will guide you through the process of problem solving and creating
simple computer programs. Based on the ECDL Computing syllabus, this module will help
you understand how to use computational thinking techniques to identify, analyse and solve
problems, as well as how to design, write and test simple computer programs using well
structured, efficient and accurate code.
• Understand key concepts relating to computing and the typical activities involved in
creating a program.
• Understand and use computational thinking techniques like problem decomposition,
pattern recognition, abstraction and algorithms to analyse a problem and develop
solutions.
• Write, test and modify algorithms for a program using flowcharts and pseudocode.
• Understand key principles and terms associated with coding and the importance of
well-structured and documented code.
• Understand and use programming constructs like variables, data types, and logic in
a program.
• Improve efficiency and functionality by using iteration, conditional statements,
procedures and functions, as well as events and commands in a program.
• Test and debug a program and ensure it meets requirements before release.
ECDL Computing has been developed with input from computer users, subject matter
experts, and practising computing professionals from all over the world to ensure the
relevance and range of module content. It is useful for anyone interested in developing
generic problem solving skills and it is also provides fundamental concepts and skills
needed by anyone interested in developing specialised IT skills.
Once you have developed the skills and knowledge set out in this book, you will be in a
position to become certified in an international standard in this area – ECDL Computing.
For details of the specific areas of the ECDL Computing syllabus covered in each section of
this book, refer to the ECDL Computing syllabus map at the end of the learning materials
book.
LESSON 12 – LOOPS................................................................................................................ 97
12.1 Looping ........................................................................................................................... 98
12.2 Looping with Variables .................................................................................................. 100
12.3 Variations on Loops ...................................................................................................... 101
12.4 Putting It All Together.................................................................................................... 103
12.5 Review Exercise ........................................................................................................... 107
Pattern Recognition
A pattern is a repeated design or feature, like the chorus of a song or a motif on
fabric or wallpaper. Patterns can also be found in activities, for example, several
different recipes may involve setting the oven to a certain temperature and waiting
for it to heat up. This is known as a shared pattern. Pattern recognition involves
finding patterns or repetition within complex problems or among smaller related
problems.
In the figure above the first set of coloured blocks has been split in two to highlight
the presence of a pattern that is being repeated.
Abstraction
Abstraction is the process of extracting the most important or defining features
from a problem or challenge. The extracted features provide the information to
begin examining the challenge and find potential solutions. It involves filtering out
unnecessary details and only looking at information that is relevant to solving the
problem. In the task of baking biscuits, it is not important whether you are right or
left-handed. The information that is relevant to completing the task includes the
ingredients, the order in which you mix them in, and the duration and temperature
of cooking.
In the following example, any unnecessary details have been removed from the
second image of the dog so only the information relevant to solving the problem
remains – there is a dog and it wants food.
Decomposition
Decomposition involves breaking a complex problem down into smaller, simpler,
easier to understand problems. The smaller problems can be broken down into
smaller and smaller problems until they are easy to understand and manage. In
the task of making biscuits, a smaller problem might be to ensure that the oven is
at the right temperature. The image illustrates how a complex problem can be
decomposed into smaller and smaller parts or problems.
Smaller
Problem Smaller
Smaller
Algorithms
An algorithm is an organised set of instructions which provides steps for solving a
problem or completing a task. For example, an algorithm could be the instructions
in a recipe or the calculations for a computer to follow. Algorithmic design is the
process of creating these well-defined instructions in the form of steps to solve
Evaluation
Evaluation involves validating the design, of a product or an algorithm, by
checking that it does what it’s meant to, or solves the problem.
Generalisation
Generalisation is taking a solution and finding a way to make it useful in a wider
set of circumstances. For example, you might use symbols instead of words on a
products’ controls so it can be used regardless of the language spoken. In the
following image the basic structure of the flower is always the same and can be
used repeatedly but the characteristics such as the colour and shape can be
varied.
These six computational thinking skills work together to solve complex problems
in computing and beyond.
Steps
Example: Designing a Washing Machine
Abstraction
The first step in designing a washing machine is to determine the goal – for
example it should be able to wash vigorously or gently, at a low or high
temperature and produce clean clothes. The design phase involves listing the
features to achieve this goal. Abstraction can be used to help the designer filter
out what is relevant and what is not when listing the features to include and
exclude. Details that aren’t relevant might include things such as the colour of the
washing machine or whether the load to be washed has six pairs of socks or three
pairs of socks.
Details that are relevant are those that affect the overall functionality and they
might include things such as water temperature and whether a programme is for
delicate or hard-wearing fabrics. These details are relevant to solving the problem
of producing clean clothes without damaging them.
Decomposition
Decomposition can be used to break the problem down into smaller, more
manageable problems, such as:
In turn these small problems may be decomposed into even smaller ones:
Algorithms
Algorithms can be designed to specify the precise steps that the machine should
follow for different wash cycles. And there are many other algorithms needed. For
example an algorithm can be designed to specify the sequence of precise steps to
be followed to manufacture the washing machine.
Evaluation
Designing a product is a big challenge, so early designs will be continuously
evaluated. Through evaluation, the designers learn where and how the design can
be improved. For example, if while testing a machine, water leaks out, the design
can be modified to prevent this happening in future.
Generalisation
The washing machine design may also be improved by making it universal, for
example using symbols instead of words on the controls, so that it can be used by
people regardless of their language, or by designing it to work on 110 volts as well
as 220 volts for use in different countries. If the design is modified in this way,
then it has been generalised.
Pattern Recognition
Pattern recognition has an important role and along with the other five techniques
it can be used multiple times throughout the different stages of the design
process. It can help with abstraction by highlighting the similarities and
differences in aspects of a problem. Pattern recognition can also help with
generalisation; where aspects of one particular problem can be related to more
general problems. Similarly, evaluation of the design helps to generalise it, by
evaluating how the design may be applied in different settings.
Steps
Example: Organising a Music Festival
Abstraction
To begin to plan a music festival you must understand what a music festival is, so
the first step could be to list essential things that a music festival should have:
• Musicians
• Venue
• Marketing and publicity
• Tickets
• Staff etc.
There will be other details to consider in organising the festival, which are not
essential such as the colour of the tickets and the exact wording on the tickets.
© 2017 «PageFooterText» Page 7
Lesson 1 – Thinking Like a Programmer ECDL Computing
These can get in the way of the initial planning, and can be worked out later.
Using abstraction, the non-essential details can be removed from the plan for the
moment.
• Someone to liaise with the venue where the festival will take place.
• Someone to deal with publicity.
• Someone to work on bookings and tickets.
These smaller challenges can be further broken down into even smaller problems
to solve. This is decomposition of the problem and an example of applying the
methods of computational thinking.
For example the problem of organising the venue could be broken down as
follows:
And the smaller problem of the car parking arrangements can be broken down
into small processes or decomposed. And simple algorithms can be created,
including some of the following:
• How to make the festival interesting so that people will want to go?
• How to advertise to your intended audience event in a cost-effective way?
And the booking and ticketing process can also be decomposed further. For
example the ticketing process can be broken down into a set of steps, and an
algorithm created covering design, printing, purchase, delivery, concessions,
refunds etc.
• Where?
• When is it available?
Venue
• What about parking?
• How to issue?
• What about concessions?
Tickets
• How to check tickets?
Evaluation
After the event has run, it can be helpful to gather feedback about what worked
well and what did not work so well. This is a way of evaluating the plan. If the
festival runs again, the lessons learned from the evaluation will improve the
following year’s event.
Generalisation
Generalisation is relevant too. A team that has run a music festival might go on to
more ambitious goals, for example a series of festivals in a tour, or increasing the
duration of the festival, adding more acts, or more kinds of music. The existing
solution or formula is reused, but generalised to include new elements.
Steps
Example: An algorithm for sorting people by height
In this example you want to sort the people in your class by height. To do this, you
could decide on a number of steps to perform:
This set of steps is an algorithm. However, it is not very detailed. Step 3, for
example, could be further decomposed into smaller problems:
Once designed correctly, this algorithm for sorting people by height could be
modified to solve slightly different problems. A small variation on the algorithm
could instead sort people in the class by order of birthday. And with further
modifications, it could be used to find out if any two people have the same
birthday.
Concepts
Algorithms for Computers
In the algorithm for sorting people by height the instructions are detailed enough
for a human to follow, but they aren’t detailed enough for a computer to follow. A
computer needs to be instructed using a computer language, which is much more
detailed and precise than human language.
So for a computer to follow the instructions in the algorithm, the algorithm must be
converted into a language that the computer can understand. An algorithm
expressed in a form that can be understood and executed by a computer is known
as a program.
When the computer obeys the steps in a program, it is said to run or execute the
program. So a computer program is written in a computer language and the
computer works by running or executing the program.
5. A program is:
a. The detailed rules and regulations of a game or sport
b. An algorithm expressed in a form that is suitable for a computer
c. The collection of laws and regulations that determine what buildings can be
built legally at a particular place.
d. A sequence of instructions for a person to follow, e.g. a recipe for baking a
cake.
6. Which of these is least likely to be a way that algorithms are used in computational
thinking?
a. An algorithm may lead to a computer program that when run solves the
problem
b. An algorithm may lead to a computer program that employs intuition to derive
better solutions.
c. An algorithm may provide a step by step guide for manufacturing something.
d. An algorithm may provide a step by step guide for processes involving people,
money and resources.
Chocolate cake:
Set oven to 180oC
Butter two 9” cake pans
Mix ingredients with a whisk for one minute
Transfer mix to cake pans
Bake for 30 mins
Allow to cool
Ice and decorate cake.
Gingerbread men:
Cream the ingredients together
Set oven to 190oC
Roll out the dough to about 1/8” thickness, and cut into gingerbread men
shapes.
Bake until edges are firm, about 10 minutes.
Blueberry muffins:
Set oven to 185oC
Grease 18 muffin cups
Cream butter and sugar until fluffy
Add other ingredients
Spoon into muffin cups
Sprinkle with topping
Bake for 15 to 20 mins.
8. For designing a program for cooking for a robot chef to use, which of the following
would be the most relevant detail?
a. The colour of the robot.
b. What quantities of each ingredient to use.
c. Which shop the ingredients were bought from.
d. Whether the programmer is right or left handed.
Formal Language
A formal language is strictly structured, with exact and precise rules. It is used in
mathematics, chemical equations and computer programs. It is clear and
unambiguous.
Computer languages are formal languages. One way formal languages can avoid
ambiguity is by using brackets to group words and terms, and by avoiding words
like ‘it’ or ‘he’ or ‘she’ where it might not be clear what ‘it’, ‘he’ or ‘she’ refers to.
Here are three different types of brackets used in formal languages. Each type of
brackets has a different function, and they can be used to define things like which
order a set of steps are expected to be performed in a program.
BRACKET NAME
() Round brackets, or
parentheses.
[] Square brackets.
Steps
Example: Ambiguity with ‘and’ and ‘or’
If you ask someone what flavour of sweets they would like, they might say:
“Blackberry and Lemon or Raspberry and Orange”. You understand the response,
but for a computer to understand the sentence, the words need to be grouped
correctly.
For the computer, you need to write (Blackberry AND Lemon) OR (Orange AND
Raspberry)
OR
Whereas if you write Blackberry AND (Orange OR Lemon) AND Raspberry, the
computer interprets it as:
AND AND
There are many different computer languages. These learning materials use a
popular computer language called Python. Some other common languages are
Java and C++.
Concepts
Computer Code
The text of a computer program, written as a series of instructions for a computer
to execute, is known as code. Different computer languages use different styles of
code with different rules and ways of organising instructions, often referred to as
syntax.
There are two kinds of computer code: source code and machine code.
Source code is the code written by the programmer that humans can understand.
It is typed into a computer, usually as text, punctuation and symbols, which
contains instructions for the computer. If you learn the formal programming
language and its rules (e.g. Python), you can write source code.
Machine code is a series of 1’s and 0’s created by the computer from the source
code that the computers electronic circuits can understand. Creating machine
code from source code is known as compiling or interpreting the source code.
Steps
Example: Machine code to lock a door
The instruction to lock a door written in source code might look like this:
Lock( door )
Although this isn’t grammatically correct, it does make some sense to people
reading it.
A computer reading the source code instructions sees the letters ‘L’, ‘o’, ‘c’, ‘k’, ‘(‘,
and so on. The instructions aren’t in a format the computer can act on directly.
Instead the computer needs the instructions to be converted into a format that it
can understand and obey.
The computer has electronic circuits that act on certain patterns or combinations
of 1’s and 0’s. Below is an example of what some patterns of 1’s and 0’s might
mean.
In reality the full range of possible machine code instructions for a computer would
be much larger. There would, for example, be many instructions for performing
arithmetic.
Source code is converted into machine code before a computer obeys the
instructions. ‘Lock( door )’ would be translated to 0100 and the computer could
then obey that instruction.
In this simple example, one source code instruction ‘Lock( door )’ corresponds to
one machine code instruction, 0100. Usually, a single line of source code
requires several machine code instructions one after the other, in the correct
sequence.
The earliest computer programmers converted the source code into machine code
manually, and created and documented the series of 1’s and 0’s themselves. The
invention of programs to translate source code to machine code made it possible
to write larger and more complex computer programs.
For example, a specification might include the requirement “The program SHALL
dim the screen if the computer has not been used for one minute, to save
electricity”. Once the program is written, the program can be tested by leaving the
computer running for a minute and checking that the program does indeed dim
the screen. The following image describes the possible progression in work on a
computer program from development to execution.
This interactive
holiday app…
Description
Specification
If( not(photo_ready())) :
wait
Source Code
01101101 10110110
11000010 10100
Machine Code
The following diagram shows some of the main stages and activities in the
creation of a program.
Analysis
Pattern
Recognition
Abstraction
Design
Decomposition
Algorithmic Design
The Description The Specification
document is most
relevant at these stages
document is most
relevant at these stages Programming
Programming/
Coding
Testing
Evaluation
Enhancement
Generalisation
Analysis
This involves defining the problems to be solved more clearly. Analysis is largely
a process of abstraction, listing all aspects of the problem, identifying the relevant
aspects and how they relate to each other.
Design
This involves working out the algorithms (sets of steps to follow) to solve the
problem. This uses decomposition to break the problem down into smaller parts,
and planning the design of the algorithm.
Page 20 «PageFooterText» © 2017
ECDL Computing Lesson 2 – Software Development
Programming
This involves writing the program. This includes finding a way to express the
algorithm in the chosen computer language.
Testing
This involves checking that the program actually does what was it was intended
to. Testing can uncover errors in the logic or syntax of the program. These are
covered in more detail in Lesson 15.
Enhancement
This involves adding new features to extend the program's capabilities, improve
its performance or functionality, or to generalise it for use in different situations.
The program specification is normally drawn up during the design phase. Some
of the requirements in the specification may arise directly from decomposition of
the problem into smaller problems. The program specification is examined during
testing, as each statement about the program’s capabilities must be verified.
Computer algorithms are complex problems broken down into simpler steps or
instructions. In most algorithms, the instructions are obeyed one after the other
in a sequence.
In most algorithms the order of the instructions matter. A robot chef would need to
put the cake mixture into the tin before putting it in the oven.
Instructions often use information from the world outside the computer and do
something with it. Computer programs can receive information to work on via
inputs and give results via outputs.
An input
A value from outside the computer that is needed for the instructions to be
followed. For example: a measurement of temperature, or a number typed on the
keypad of a security/alarm system.
An output
A value calculated, or an action performed, by the computer program, which is
displayed to the world outside of it. For example: a light being switched on or off,
a security alarm being set, or a message displayed on a screen.
Steps
Example: Inputs and Outputs of a Mobile Phone
A mobile phone takes in information or inputs and processes them and returns
results or outputs.
Page 24 © 2017
ECDL Computing Lesson 3 – Algorithms
• The touch screen is an important input method, for example when you use
it to type a message or tap open an application.
Yes / No Decisions
As you have seen in previous lessons, the order of instructions, or sequence, is
important in computing. In general, instructions are followed one after the other,
but sometimes there are decisions to be made on what to do next. The algorithm
can be designed to ask questions and expect an input to help decide on the next
step.
Steps
Example: Waiting for an Oven to Heat Up
Before putting a cake mixture into the oven, the oven needs to be at the right
temperature. An algorithm could include a yes / no decision to determine this. “Is
the oven at the right temperature?” A thermostat will provide the input, yes or no.
If the answer is yes, then it is ok to put the cake into the oven. If the answer is no,
the algorithm will wait a while and ask the question again.
Pseudocode:
Pseudocode is an informal way of representing an algorithm, using written
instructions in natural language, for example English. The steps in the algorithm
are written out as a sequence of instructions. An algorithm written as pseudocode
is intended for a human to read rather than a computer.
Pseudocode looks like the code that the program will be written in, but is not quite
as precise. If the pseudocode makes sense to read, then the next step is to write
the actual code for the program.
START
STOP
Page 26 © 2017
ECDL Computing Lesson 3 – Algorithms
3.3 FLOWCHARTS
Concepts
Some of the shapes used in a flowchart are shown below:
Input or Yes
START or STOP Do something IF
Output
No
Flowchart symbols
Start or Stop
The algorithm starts at the Start box and runs until it reaches a
Stop box.
Process
These boxes contain simple instructions to do something, such
as add two numbers or look up a word in a dictionary.
Input or Output
These boxes are for interaction with the world outside the
computer. For example, an input could be from a movement or
temperature sensor. An output could be an action such as
turning on or off a light.
Decision
Decision boxes allow for alternative choices in what the algorithm
does next. They often have a question in them which will have a
yes or no answer. If the answer is ‘yes’ one route is taken. If the
answer is ‘no’ the other route is taken. This is how algorithms
can go beyond simple sequences of steps.
Arrow Connector
© 2017 «PageFooterText» Page 27
Lesson 3 – Algorithms ECDL Computing
The arrow and connector are used to connect the flowchart boxes.
Arrow
A directional line drawn to connect two boxes in a flowchart. This
arrow shows the direction of flow in an algorithm. These are
often referred to as flow lines. For example, instructions in a
sequence have arrows between them.
Connector
A small circle in a flowchart that is used to connect two flow lines
together. It shows a jump from one point in the process flow to
another, for example when answering a “Yes/No” question.
Steps
Example: Flowchart for the 347347 'Magic Trick'
Start
Think of a 3 digit
number like 347
Stop
Flowchart for a numerical trick
Page 28 © 2017
ECDL Computing Lesson 3 – Algorithms
This is a flowchart for a numerical magic trick. This flowchart shows a simple
sequence, with no decision boxes. We begin the process from the Start box and
continue following the flow lines completing the instructions in each of the boxes
until we reach the Stop box.
This flowchart represents an algorithm for baking a cake. It has a decision box in
it. The decision box determines whether the cake is ready to take out of the oven,
and if not instructs the chef to wait until it is.
“Is cake baked?” is an input to the algorithm and has the input/output shaped box.
START
Mix Ingredients
Check whether
cake is baked Wait
Cake is baked?
STOP
This flowchart shows the sequence of actions for choosing a mobile phone game.
Each of the diamond shaped boxes has a question in it. The answer to the
question can be yes or no. The answer determines which box to go to next.
START
Find a Mobile
Phone Game
Choose a
different game
No No
No Do I want to
Yes upgrade to the
Yes Do I have Yes
Is it any good? enough money?
paid version?
No
Make do with
STOP the free version
Make a flowchart for getting up in the morning, having breakfast, and getting to
school.
HINTS:
2. Take some of the steps and decompose them into smaller steps detail. For
example, if you have a step called ‘make breakfast’ - that can be broken down
into smaller steps like “put bread in toaster”.
Page 30 © 2017
ECDL Computing Lesson 3 – Algorithms
• Is it raining?
• Am I late for school?
5. Add decision boxes for these questions, with different steps if the answer is
yes or no.
3.4 PSEUDOCODE
Concepts
Instead of creating a flowchart, an algorithm can be represented in pseudocode.
Steps
Example: Pseudocode for the 347347 'Magic Trick'
1. Incorrect Sequence
Here is an algorithm for baking a cake and taking it out of the oven when it is
baked and not before.
Page 32 © 2017
ECDL Computing Lesson 3 – Algorithms
The decision to wait could be wrong because there is no test to see if the cake is
actually baked. To correct a possible incorrect decision outcome, an extra line of
pseudocode is needed:
Here is an algorithm for baking a cake which is missing some important steps.
Arrow
Decision
Start or Stop
Process
Input or Output
Connector
5. The following program is supposed to drain water from a washing machine. What
error does it have?
Turn on drainage pump
Page 34 © 2017
ECDL Computing Lesson 3 – Algorithms
a. Missing instruction
b. Incorrect sequence
c. Incorrect decision outcome
d. Incorrect indentation
These learning materials use the Python IDLE programming environment, which
allows you to write, edit and run code, and save your programs as files for
retrieving later. It incorporates the command line environment, the Python Shell.
2. Double click on the icon. This will start an interactive window, as shown
below:
3. Click the mouse cursor just after the prompt >>>. This is the signal to enter
code or instructions for Python to run on the computer.
Page 38 © 2017
ECDL Computing Lesson 4 – Getting Started
• The result is that the words First Steps in Coding are displayed on
screen.
1. Locate the Python Shell icon on the computer desktop, or in your program
files.
2. Double click on the icon. This will start the interactive Shell window, as
shown below:
3. Click the mouse cursor just after the prompt >>>. This is the signal to enter
code or instructions for Python to run on the computer.
4. Type asdf
5. Press Enter
6. View the result. In this example, Python does not understand the letters
asdf. Observe the four lines in red. Python provides error messages when
it doesn’t understand what has been typed in. Usually the last line of the
error message has the most useful information about the error, in this case
“ ‘asdf’ is not defined ”.
Page 40 © 2017
ECDL Computing Lesson 4 – Getting Started
2. A new untitled window is created. Click in the main white area of the
untitled window.
7. Notice the window title changes to ‘TryIt.py’. This is the name of the
program or file.
Page 42 © 2017
ECDL Computing Lesson 4 – Getting Started
3. In the dialog that appears, select the file name “TryIt.py” or type in the file
name.
5. To run the program click on Run in the menu bar and then click Run
Module:
6. This is what you should expect to see when the program is run:
7. Pressing the F5 key on the keyboard will also run a program. Close the
results window by clicking the X in the top right corner. Return to your
program and this time press F5 on the keyboard to run the program. View
the results.
Page 44 © 2017
ECDL Computing Lesson 4 – Getting Started
10+12+15.
It uses the symbol * for multiply and / for divide rather than using x and ÷.
NOTATION MEANING
3*4 3 multiplied by 4
3/4 3 divided by 4
3+4 3 plus 4
3-4 3 minus 4
In Python:
7 multiplied by 9 is written as 7 * 9
63 divided by 3 is written as 63 / 3
The spaces between the numbers are optional and 7*9 will work just as well as 7
* 9.
Parentheses Matter
Mathematical expressions in Python can also contain parentheses, also known as
brackets, for example:
10-(6-4)
If we evaluate this expression from left to right, ignoring the parentheses, the
solution would be 0.
10-(6-4) = 0
First: 6-4=2
Then: 10-2=8
So, 10-(6-4)=8
1+7+2+3
2*2*3+4
4+3*2=?
4+3 = 7, 7*2 = 14
31*7+112*2
The two multiplication parts are done first, then the addition.
Page 48 © 2017
ECDL Computing Lesson 5 – Performing Calculations
2. Type in the expressions (calculations) after the prompts. Press Enter after
typing in each one.
If red paint costs €31 per litre and gold paint costs €112 per litre, then the cost of
7 litres of red paint and 2 litres of gold paint can be written as:
31*7+112*2
In this case, you can see that it is important to calculate what each colour paint
costs first, and then getting the total cost.
So, (31*7)+(112*2) gives the correct overall price, whereas evaluating from left to
right does not.
3. Evaluate the expression 3*4*2+8 using the Operator Precedence rule and select
the appropriate answer below:
a. 24
b. 32
c. 104
d. 120
Page 50 © 2017
LESSON 6 –
DATA TYPES AND VARIABLES
Lesson 4 - Python Expressions
For example, your age is stored as a number and we can perform mathematical
calculations on it, like compare it to that of your friend. And your name is stored as
text.
In computing data types are used to determine how to store data and what
operations to carry out on the data.
The Python data types you will use most often are: Integer, float, string and
Boolean.
Most programming languages have standard data types just with slightly different
names. For example the ‘string’ data type used in Python is sometimes referred to
as a ‘character’ data type in other languages. The character data type can also be
used to define letters or characters such as 'a' 'b' 'c' '@' etc.
Float
Describes or defines a decimal number such as 11.456, -71.3, 29.0.
Floats are also used to represent some very large or small numbers in scientific
notation. For example, 5.0e30, which means 5 followed by 30 zeroes, or 1.7e-6
which is 0.000017, which means 1.7 divided by 1 followed by 6 zeros.
String
Describes or defines a piece of text, or ‘string’ of characters. For example the
name of a person, such as ‘John Smith’. String values often arise from using the
input() command.
Boolean
Describes or defines a value which is either True or False. Boolean data types
can only ever be one of these two values. Boolean values most often arise from
comparison of numbers.
Page 52 © 2017
ECDL Computing Lesson 6 – Data Types and Variables
6.2 VARIABLES
Concepts
A variable is used in code to represent a piece of data so that the data can be
used several times in a program. A variable is like a placeholder for actual values.
It can hold the value and then retrieve it for use later.
x=3
In this case, each time the variable x is used in the program it will represent 3.
In this case, each time the variable Greeting is used in the program it will
represent Good Morning. After the assignment the variable name Greeting can
be used in place of the string 'Good Morning'.
The command print( x+2 ) will print the value 5 to the screen.
The command print( Greeting ) will print the value 'Good Morning' to the screen.
Defining a variable means defining in the code what data type the variable will
hold, for example, a number (e.g. integer, float) or a string. In Python you do this
the first time you assign a value to a variable. Python determines that the variable
will hold the data type of the assigned value.
If you assign the number 3 (i.e. the value) to the variable x, Python will assume
that x will always represent a numeric value.
x=3
If you assign the string ‘country’ to the variable q, you are telling Python that q will
always represent a string. You use inverted commas around the text to indicate
that it is a string data type.
q=‘country’
In the example, the piece of text is enclosed in inverted commas, which indicates
that it is the string data type. Any characters enclosed in inverted commas are
considered a string, even a number. In the following example 12 is a string not a
number:
Age = ‘12’
Initialising Variables
You need to assign an initial value to a variable before you can use it. The first
time a value is assigned to a variable is called initialisation of the variable.
If you try to apply a command to a variable before it has been initialised you will
get an error message. Before a value is assigned to a variable, the variable is
known as uninitialised.
Updating Variables
The value of a variable can be updated by assigning a new value to it. You update
the variable and it is automatically updated wherever it is used throughout the
program. This is an important reason for using variables as you only have to make
one update to update multiple occurrences. A variable always holds the most
recent value that has been assigned to it.
Page 54 © 2017
ECDL Computing Lesson 6 – Data Types and Variables
x=7
1. Open Python.
As well as adding numbers together, you can join strings and characters together.
To do this in Python, you can use the + symbol.
For example, initialise the variable Name to “David”, and Question to “What is
your age?”
Name= “David”
Note the blank spaces in the string. Without the spaces at the ends of the string
there would be no space between the word you and the word David and the
question would look like this:
Age = ‘12’
then Age +1 will give an error, because a number can't be added to a string.
Page 56 © 2017
ECDL Computing Lesson 6 – Data Types and Variables
To fix that, you can convert the variable Age to an integer as follows:
You can write code that asks a user to enter some information in the form of a
string, for example their name.
In Python you use the input() command to prompt the user to enter a string .
The input() command is an instruction in Python that requests the user to enter
information and the program waits until the information is entered.
5. Press Enter.
• The user is prompted to enter a string, in this case their name, using the
input() command.
• The variable ‘Name’ is initialised to contain the name entered by the user.
• The print() command is used to output the text “Your name is:” followed by
the contents of the variable ‘Name’ to the screen.
1. Open the previous example, MyName.py, using the steps you learned
earlier.
Page 58 © 2017
ECDL Computing Lesson 6 – Data Types and Variables
4. In Python, if a variable named ‘length’ has the value 200, and the instruction
‘length=400’ is obeyed, what happens?
a. Python gives an error message, because you can’t change the value of a
variable.
b. Python gives an error message, because you can’t change 200 to 400.
c. Python assigns 400 to length and length now has the value 400.
d. Python adds 400 into length and length now has the value 600.
Page 60 © 2017
ECDL Computing Lesson 6 – Data Types and Variables
b. Float
c. String
d. Boolean
Is it cold outside?
Check whether
Cake is baked Wait
No
Cake is baked?
Yes
Computer programs work with the outcomes True and False rather than Yes or
No.
True and False are important concepts in computing because we need a way to
test if certain conditions exist in order to control what happens next in the
program.
One way in which Python programs use Boolean expressions is to test the size of
a numerical value against another value and give a ‘True’ or ‘False’ result. It
carries out this test by using a comparison operator. A comparison operator
compares the values on either side of them and decide the relation among them.
They are sometimes referred to as relational operators.
99 > 7
Here the operator ‘>’ compares the values 99 and 7 to see if the value on the left
is greater than the value on the right. If so, the result is True, otherwise the result
is False.
There are six comparison operators. In the table below X and Y are variables
holding numerical values:
NOTATION MEANING
X == Y X is equal to Y
Page 64 © 2017
ECDL Computing Lesson 7 – True or False
X != Y X is not equal to Y
Note: Some other languages may use <> as not equal to and = as equal to.
Python 3.x doesn’t use <> and it uses == instead of a single =.
1. Open Python.
3. Make up your own examples. Anticipate what the answer to each should
be. See whether the answers, True or False, are what you expect them to
be.
and
- Combines two Boolean values and gives a result - True if both values are True,
otherwise False
Expression Result
True and True True
True and False False
False and True False
False and False False
or
Combines two Boolean values and gives a result - True if either one or both
values are True, otherwise False.
Expression Result
True or True True
True or False True
False or True True
False or False False
not
Converts a single Boolean value from True to False, or False to True.
Expression Result
not True False
not False True
Boolean expressions can include the use of both comparison operators and
Boolean operators. This is an example:
In such mixed expressions, the comparison operators are evaluated before the
Boolean operators. That’s because of the rules of operator precedence which
we’ll come back to later in this lesson.
1. Open Python.
Page 66 © 2017
ECDL Computing Lesson 7 – True or False
3. Think of some combinations to make sure that you understand what and,
or and not do.
Y = 200
This initialises the variable called Y to the numeric value 200.
A = False
This initialises the variable called A to the Boolean value False.
The next example uses a Boolean variable. The variable is called True_or_false.
Notice that underscores are being used between the words of the variable name.
Python treats an underscore within a variable name like other letters, so
True_or_false is one variable. If you use spaces instead of underscores, Python
will treat the words as three separate things and give an error.
Page 68 © 2017
ECDL Computing Lesson 7 – True or False
Let’s assume for example that A is False, B is True and C is True. Putting these
values into the two expressions gives different results:
Note how the use of parentheses changes the result of the expression A and B or
C.
The table below is a partial list of the order in which the most important operators
are applied, or take precedence. In the list below, the operators at the top of the
list are applied before operators at the end.
Page 70 © 2017
ECDL Computing Lesson 7 – True or False
Symbol Operation
or Boolean or
An expression like:
A or B and C
Will be evaluated as:
A or (B and C)
A complex expression such as:
The operator precedences for *, /, + and - are used so frequently that it is rare to
use parentheses to clarify the order of evaluation.
3. In Python, which expression could give a different result to the other three?
a. a < b < c
b. c > b > a
c. a < b or b < c
d. a < b and b < c
Page 72 © 2017
LESSON 8 –
AGGREGATE DATA TYPES
List
A collection of values. Lists can change by adding items to or removing items from
them or changing an item in a list. Python can display an entire list of values. It
can also retrieve items from a list. (The Python ‘list’ aggregate data type fulfils the
role of an ‘array’ in other programming languages.)
Tuple
A tuple is just like a list, except once it has been created it can’t be changed by
rearranging, adding or removing items or modifying individual items.
While the restriction on tuples might appear to make them less useful than lists,
tuples have two important advantages:
1. Retrieving items from Tuples is faster than retrieving items from lists.
2. A programmer reading code for tuples will not need to check if values were
changed.
An element in a list or tuple can be selected by giving the name of the list or tuple
and then the number of the element in square brackets. For example, element 3
of the list called pets is:
pets[3]
Elements are referenced by numbers starting from zero, so in the list:
[“cat”,“dog”,“hamster”,“goldfish”,“rabbit”,“turtle”]
pets[0] = cat
pets[1] = dog
pets[3] = goldfish
Page 74 © 2017
ECDL Computing Lesson 8 – Aggregate Data Types
8.2 LISTS
Concepts
Python has some built-in methods for working with lists. For example, this
command will sort the list called pets:
pets.sort()
1. Open Python.
2. Create a list called pets, by enclosing the elements in square brackets, as
you see in the screenshot below.
3. Explore individual elements of the list by using numbers in square brackets
as shown.
1. Open Python.
2. Create a program file called ManyNames.py.
3. Type in the program code as below, using the names of some friends if you
like, rather than the names given here.
8.3 TUPLES
Concepts
Tuples in Python
Tuples are created in the same way as lists, but using round brackets instead of
square brackets.
You cannot sort a tuple with the sort() command, as Python does not allow
rearrangement of a tuple’s elements.
If a variable is assigned to a tuple, Python still can’t make changes to that tuple.
Python can however assign a new variable to the tuple i.e. replace the tuple with a
new one. This sequence shows an example of how you might replace one tuple
with a new one:
animal_tuple = (‘cat’,’dog’,’pig’)
animal_tuple = (‘elephant’, ‘tiger’, ‘giraffe’)
One common use for a tuple is to hold the x and y position of a point on the
screen. Instead of having two variables, one for x, and one for y, a single tuple
variable can hold both values. When the x and y values are needed, they can be
extracted from the tuple.
(A list could be used in the same way as a tuple to hold the x and y position of a
point on the screen but a tuple is more efficient.)
1. Open Python.
2. Use the code shown below to create a tuple containing names of fruit.
3. Show the tuple's value by typing 'fruit'.
Page 76 © 2017
ECDL Computing Lesson 8 – Aggregate Data Types
1. Open Python.
2. Use the code shown to create a tuple containing 40 and 150.
3. Extract x and y from the tuple.
4. Show the value of x and y.
Page 78 © 2017
LESSON 9 –
ENHANCE YOUR CODE
- Python Code
In reality python programs can be quite large and contain many instructions. They
are often worked on by more than one programmer at different stages. It is
essential that a program’s code is ‘readable’ i.e. the reader can easily understand
what the program does and why.
The same general techniques for making code easier to understand apply to all
programming languages, they are:
• Use of comments
• Organisation of code
• Descriptive names
9.2 COMMENTS
Concepts
A comment is a piece of text explaining what some part of the code does. It is a
short description of a piece of code that humans can read but the computer will
ignore, designed to help programmers understand what is happening within a
program. Appropriate comments are a characteristic of well-structured and
documented code. Comments on the code should help the author and other
people understand what each section of code is doing.
Comments start with a hash, #, and go on to the end of the line. They appear in
red in the Python editor.
The red text after the # to the end of the line is not considered by Python when it
is running the code. The text is just there for programmers use.
# This is a comment
Page 80 © 2017
ECDL Computing Lesson 9 – Enhance Your Code
A block is defined as a group of adjacent lines that are indented the same
amount. Indentation is used to make program code easier to read and
understand. Many code editors perform the indentation automatically.
Blocks are usually named by using the word 'def' followed by the name, chosen to
describe what the code does. (This is explored further in lesson 12 Procedures
and Functions.)
The name (“def name”) is entered first, and then the start of the block is shown
with an indentation of the line. The lines of code in a block have the same
indentation, and are a sequence, so they are run one after the other.
Giving meaningful to variable names will also make more sense to the reader.
Variable names should be carefully selected so that they give a clue as to what
the variable is used for.
In our list example from lesson 8, the variable name pets could have been used
instead for a list of fruit:
pets=[‘pineapple’,’mango’,’kiwi fruit’]
print( pets[1] )
would print:
‘mango’
Page 82 © 2017
ECDL Computing Lesson 9 – Enhance Your Code
3. Review the code you have created so far in ECDL Computing and see
where you might improve its readability by using the techniques from this
lesson.
Page 84 © 2017
LESSON 10 –
CONDITIONAL STATEMENTS
Lesson 6 - Flow of Control
When programmers use the term 'statement' they are referring to small
components of code like print().
10.2 IF STATEMENT
Concepts
In a flowchart, a decision box can be considered a complete standalone unit. The
decision box has a True or False outcome that allows a choice to be made on
what the code executes next.
In Python, conditional statements use a structured format and layout, and are
written with the keyword if followed by a boolean expression to evaluate the
condition, and then a colon.
For example:
The indented block of code on the next line (the print() command in this case) will
be obeyed if the expression is evaluated as true.
Page 86 © 2017
ECDL Computing Lesson 10 – Conditional Statements
The boolean expression (12 (Age ) > 14 ) in the if statement is called a logic test.
A Logic test is an expression that gives a Yes or No, True or False answer. The
answer affects what code runs next.
If expression
statement if true
In pseudocode the logic test may be expressed in natural language such as:
The same logic test would be shown as text in a flowchart like this:
Is balance>=Price?
1. Open Python.
2. Create a new program file called NameLen.py Write the code as shown
below. Be sure to use a colon as shown at the end of the line that starts
with the keyword if.
The code is written with the if statement as before, and a new keyword else,
followed by a colon, to add code that runs if the logic test is False.
if expression:
statement if true
else:
statement if false
For example:
else
The indented block of code on the next line (the print() command in this case) will
be obeyed if the expression is evaluated as true.
Note: The ‘else’ is not indented, it starts at the same indentation level as the 'if'
keyword. When you try to the keyword ‘else’, Python will initially indent the word,
so you will have to press the backspace key to get the correct level of indentation.
3. When you reach the point of typing in the 'else' press the backspace key to
cancel one level of indentation.
8. Type in a longer name to see the code running for the case where the logic
test is false.
Page 90 © 2017
LESSON 11 –
PROCEDURES AND FUNCTIONS
11.1 SUBROUTINES
Concepts
One piece of code may be used more than once in different places in a program.
This is called a subroutine.
A subroutine is a block of code that can be called up and run many times in a
program. For example a subroutine could be used to display the date or time on
the computer screen.
In Python the keyword ‘def’, (short for 'define'), is used to give a name to a
subroutine. We can call or invoke a subroutine from anywhere in the entire
program by referencing its name. The subroutine will run and when it has finished,
the main program resumes from before the start of the subroutine.
A subroutine can perform a calculation, and return the answer or value to the
program. This is called returning a value.
Function
A Function is a subroutine that calculates a value for the program that contains it.
Procedure
A Procedure is a subroutine that executes an action, but does not return a value.
Python comes with some subroutines, i.e. functions and procedures, already
defined.
Page 92 © 2017
ECDL Computing Lesson 11 – Procedures and Functions
program resumes from where the input() function was called from in the
program.
This piece of code defines a function called ‘stars’ which has a parameter called
‘number_of_stars’ which determines the number of stars to return in a string.
There are three print statements in the program for us to check that the function is
working correctly.
1. Open Python.
2. Create a new file called Arrow.py.
3. Type in the first block of code from the screenshot below, with the def
statement and all the indented code lines to create a new function.
4. When you type in the three print statements, you call up the function three
times.
Note: The program runs in sequence from the first print statement.
The first print statement prints one star on the first line.
The second print statement prints two stars on the second line.
The third print statement prints three stars on the third line.
The quantity of stars printed on each line is dependent on the value of the
parameter number_of_stars in each print statement.
© 2017 «PageFooterText» Page 93
Lesson 11 – Procedures and Functions ECDL Computing
1. Open Python.
2. Create a new file called Lines.py.
3. Type in the two blocks of code from the screenshot below, with the two def
statements and all the indented code lines to create two procedures.
4. Then type in the print statement and next, the two lines to invoke the two
procedures in the main body of the program.
5. Save the program and run it to see the result.
Page 94 © 2017
ECDL Computing Lesson 11 – Procedures and Functions
• The program calls the procedure line_vert which prints a vertical line of
stars on the screen. After executing this procedure, the program resumes
with the next instruction which calls another procedure called line_horz.
• Both procedures run but don’t return any values to the program.
3. A parameter is:
a. A value which is passed in to a procedure or function for it to use
b. A way of measuring distance approximately, that can makes some code
simpler.
c. A way for a program to do several things at the same time.
d. A block of code with a specified number of lines to it.
Page 96 © 2017
LESSON 12 –
LOOPS
• Define the programming construct term loop. Outline the purpose and
benefit of looping in a program
• Recognise types of loops used for iteration: for, while, repeat
• Understand the term infinite loop
• Use iteration (looping) in a program like: for, while, repeat
Lesson 12 – Loops ECDL Computing
12.1 LOOPING
Concepts
Up to this point we have created programs that work sequentially, i.e. statements
are executed in the order they are written, like following a recipe step by step. If
we need to carry out the same step several times, we can use what’s known as a
loop in computing.
A loop is represented in flowcharts where an arrow from a decision box goes back
to an earlier box in the sequence. Examine the flowchart for baking the cake
below. Checking the cake to see if it is baked is a step that could be repeated
several times before the cake is ready to be taken out of the oven. This
repeatable step is represented by a loop – check cake, if not baked, wait 5
minutes then check again.
Check whether
cake is baked Wait 5 minutes
No
Cake is baked?
Yes
A loop in a flowchart
Using a loop to repeat an action is one of the most useful techniques in coding.
Looping code is present in most programming languages with slight variations on
naming conventions e.g. ‘repeat’ is used to determine how many times to loop in
some languages; we’ll see later in this lesson that ‘while’ does the same thing in
Python.
Page 98 © 2017
ECDL Computing Lesson 12 – Loops
for i in range( 10 ):
statement
• The keyword 'for' is followed by the name of a variable, in this case i,
keeping count of the repeats of the loop. The variable i will have an initial
value 0, and after each time the loop is run, it increments to 1 then 2, and
so on up to 9.
• The words 'in range()' with a number inside the parentheses followed by a
colon, indicating how many times the loop will run
• An indented line of code with a statement will be executed 10 times.
1. Open Python.
print('***********')
This will work but it is not efficient – what if you wanted to print 599 stars?
This is where loops save a lot of programming time and lead to shorter code. We
can write a loop to print 10 stars, 42 stars or 599 stars, depending on a value.
1. Open Python.
for i in range( 10 ):
statement
The indented code block after the ‘for’ line is said to be 'inside the loop'.
• Code before the loop is executed and then the loop is executed.
• Code inside the loop is executed multiple times.
• Code immediately after the loop is executed only after the loop has finished
repeating the code in the indented block.
So far we have looked at the basic loop but there are other variations of loops that
we can use as well.
Another kind of loop uses a logic test rather than range(). It's called a while loop.
A while loop tests a boolean expression and repeats execution of the loop as
long as (ie While) the boolean expression is true.
• The example that follows will initialise a variable x to 3000, and keep
dividing by 2 while x is greater than 0.5.
• Then it will stop.
1. Open Python.
In a while loop, if the logic test is always true, the loop will repeat forever. It then
becomes an infinite loop.
An infinite loop never stops. It uses the key words "while true", followed by a
colon.
As we usually want a program to stop at some point, infinite loops usually indicate
an error.
2. Modify the logic test so that the line reads While True:
4. You can stop the program by opening the menu and clicking on Shell,
Restart Shell.
Python can be used to write a program that draws an arrowhead like the one
shown below:
This task could be done with lots of print() statements. However, it can be done
with fewer instructions by using loops, functions and procedures.
To draw the arrow, each row of stars needs to be horizontally centered, rather
than aligned to the left. There is a function to do that. It’s called center(). If the
variable named answer holds a string of stars, the following line of code adds
spaces before and after the stars to make 30 characters in all.
answer=answer.center(30)
4. To get a more arrow-like shape the first row should have one star, the
second three stars and the third row five stars. Change the parameter
value in each print statement, as follows, to fix that:
We can create and expression and write a subroutine to create the arrow head
and reduce the amount of code needed. We need 10 rows of stars to make the
arrowhead.
i*2+1
1. Take a moment to review how the program works before running the code:
• The program begins by executing the procedure arrow_head().
• The variable i will have ten values from (0-9) and so the arrow_head()
procedure will run ten times, each time calling the function stars(). This
is an example of one subroutine calling another.
• The function stars() contains a variable called answer this variable will
hold a string of stars for each print statement.
2. Run Arrow.py to see the arrow head that the code draws.
Libraries
pygame
An optional library for working with graphics and animation.
Boilerplate code
When using boilerplate code or a library it is not necessary to know the details of
how the algorithms in boilerplate code or library work.
The learning materials include boilerplate code to initialise and use the libraries.
Python uses the import statement to make code in libraries available to use.
The first version uses the keyword import followed by the name of the library.
When using this version of import, functions from the library have the name of the
library first, then a dot and then the function name. An example is shown below:
Running this example will give a random fruit name, for example, as shown below:
When using this version of import, functions from the library do not need to have
the library name before them. An example is shown below:
LIBRARY PURPOSE
time Library
There are two particularly useful functions in the time library. They are usually
used together:
FUNCTION PURPOSE
The strftime function uses 'format specifiers' to describe exactly how it wants the
string result to look. For example, the letters '%Y' are replaced by the year, so the
string 'In the year %Y' could be changed to the string 'In the year 2001' by strftime.
%d Day of month 15
%m Month as a number 9
%M Minute as a number 22
%p Either AM or PM PM
%S Seconds as a number 56
%x Date 15/09/76
%X Time 17:22:56
Example: A timestamp
In this example strftime is used to print a timestamp. This example uses many of
the format options from the table above.
3. Run the program to get the following result. The time and date will be the
current time and date, rather than the time and date shown here.
random Library
Two useful functions in the random library are choice and randint.
FUNCTION PURPOSE
math Library
FUNCTION PURPOSE
In addition the math library has the value for the mathematical constant pi.
13.3 EVENTS
Concepts
The flow of a program can depend on certain actions happening. Users can
trigger these actions by, for example, using the mouse to click on a graphic they
see on screen, pressing a key on the keyboard or clicking a link in a browser
window. In Python programming these actions are called events.
Events are used extensively in games. Events that determine the movement of
game’s character are triggered by user input, for example: using the arrow keys to
move the character in a particular direction, using a mouse click to make the
character jump etc.
In some computers, the battery being low would trigger an event. This may cause
a message to display to suggest recharging the battery.
Event Handlers
Some computer languages have a system of 'registering' functions that are called
when certain events occur. We can recognise these functions by their names
which begin with the word 'On' followed by the name of the event. For example
'OnClick' is called when a user generates an event by clicking anywhere on the
screen.
Python has a library called turtle. It is a simple drawing package included in the
Python installation. To use this library we must use the import command at the
start of our program.
The comments in the program explain what each of the ten subroutines do. The
program continuously loops, checking on each pass to see if an event has
happened. When an event is triggered, the program calls the subroutine assigned
to that event. When it finishes it returns to the main body of the program.
• The first four onkey event handlers are used to determine if any arrow keys
have been pressed on your keyboard. Subroutines h1-h4 are invoked once
a keypress is detected. These are keyboard events.
• The next four onkey event handlers are used to detect if either p,d,b or w
keys are pressed on the keyboard, again calling the associated subroutines
h5-h8. These are keyboard events.
• The next event handler is used to detect a mouse click and triggers and
event if detected and then runs the h9 subroutine. This is a click event.
• The last event handler is used to trigger and event when a timer times out.
Once the time has elapsed, the subroutine h10 is run.
• Note how the pointer changes from black to red after 5 seconds. This is the
timer event triggering in the program.
• Note how when you press the arrow keys on the keyboard the pointer
moves and draws lines. These are keyboard events being triggered for
each arrow press.
• Press p on the keyboard turns the pen off, another keyboard event.
• Press d on the keyboard turns the pen on, another keyboard event.
• Pressing b or w on the keyboard changes the pen ink colour. These are
keyboard events.
• Finally click your mouse anywhere on the screen. The mouse pointer turns
180 degrees. You have just triggered a click event in the program.
In the check_for_quit() function, a for loop repeatedly checks to see if the Quit
event has occurred in Pygame. The QUIT event is triggered when the user clicks
on the X in the top right of the Pygame window. If that event is detected, the
check_for_quit() function returns True. If it is not detected, check_for_quit()
returns False.
The second piece of highlighted code, the call to clock.tick() function is related to
event handling too; it sets how frequently the while loop runs which in turn
determines how often the screen is updated.
We don’t need to know how boilerplate code works in detail. We need to know:
• That tuples are used to define some colours used in painting the screen.
• That the boilerplate code imports from the random library to get the function
randint.
• That it has an event loop, and what events are.
• That it uses randint to generates a random integer.
1. Locate and open BoilerPlate.py supplied with these learning materials. (you
don't need to type boilerplate.py code in yourself).
2. Look at the lines after the comment # Import the ‘pygame’ library. The three
lines with ‘import’ are all about using libraries:
• ‘import pygame’ allows us access to the pygame library so that it is
available to use.
• Initialises the Pygame library. That library has many variables inside it
that need to have their initial values.
• It defines and initialises two colours, GREY and GREEN. The round
parentheses indicate that these colours are defined as tuples with three
integer values.
• It creates a variable called screen that is a window 400 pixels wide and
300 pixels high.
3. Scroll down - the boilerplate code defines some procedures for plotting
points and blobs. Read the comments describing each subroutine
The subroutines are explained below in a bit more detail than they are in
the comments. This section of code provides utility functions and
procedures.
• plot_point will plot a green dot on the screen. It uses the numbers 400
and 300, which are the width and height of the screen, to scale the point
to the right position on the screen.
• draw_blob will draw a green circular blob on the screen. It also prints
the coordinates of the blob.
4. Scroll down - the next part of the boilerplate code is concerned with events.
Read the comments on the event processing code.
Notice that check_for_quit() is a function. It returns a boolean value.
Notice that do_eventloop() is a procedure. It does have the return keyword
in it, but that return does not return a value.
5. Scroll down
The remaining code gives two ways to draw the screen.
These two procedures give two choices for ways to use the event loop.
• draw_once() will run our drawing code once, then wait for the user to
quit the graphics screen.
• draw_repeatedly() will run our drawing code over and over, checking
each time to see if the user has quit. This procedure is suitable for
animation.
To use Pygame, make a copy of the boilerplate code, and then add your code to
it.
Pygame has a 2D graphics library. Pygame code can use a loop and random
numbers to show the principle of getting the computer to do the repetitive work.
Code can draw and animate one blade of grass and that code can then be put
into a loop to draw and animate many blades of grass.
In the following Pygame example the ‘blades of grass’ are just green lines.
4. Review the following points about this code. Check how these points relate
to the actual code.
Changing GREEN to be the tuple (0,0,255) would give blue grass instead.
• draw_blade() has three parameters, i, s and t, but at this stage only one
of the parameters, i, is used. Subroutines do not have to use all the
parameters that are passed to them.
• i is the number of the blade of grass. i sets the position of the blades of
grass, x.
The picture of grass currently has straight lines for the grass. To make the
blades of grass taper, replace the code that says draw_line().
• The new list variable ‘shape’ holds coordinates for four corners of that
blade of grass.
• draw.line has been got rid of. The two gfxdraw commands draw the
outline of the shape and then the inside, respectively. Change the
outline to a different colour to GREEN to show this.
9. The next step makes two more changes to what the program does:
There is only one significant code change involved. It affects the variable
dx. dx moves the tips of the grass left or right. 0 means no displacement
left or right. A negative dx moves the tip left. Positive moves right. The
change in the code changes the instruction dx = 0 to have a calculation for
dx.
• The 2*t*(i-15) isn’t random. It makes the tips of the grass spread out. If
this part of the expression is left out from the code the tips will just move
randomly, but they won’t spread out.
The printed picture doesn’t show that the grass is now moving, but does
show how it has spread out.
3. The string named greeting has the value ‘Good’. Which command sets it to have the
value ‘Good Morning’?
a. greeting = ‘Good’ + greeting
b. greeting = greeting + “ Morning”
c. greeting = ‘Good’ + ‘Morning’
d. greeting = [‘Good’, ‘Morning’]
4. The tuple named colour has the value (0,0,255). Which command sets it to have the
value (255,0,255)?
a. colour[0] = 255
b. colour[1] = 255
c. colour = ( 255 , 0+0 , 255 )
d. colour = 255,0,255
5. Which of the following does not generate events in Python with Pygame?
a. Clicking on the mouse.
b. A timer.
c. Input from keyboard.
d. Battery low.
14.1 RECURSION
Concepts
The waving grass example from lesson 13 and the arrow example from lesson 11
involved subroutines calling other subroutines. This is one of the ways we
decompose a problem in computing. Remember decomposition is about breaking
a problem down into smaller problems. Subroutines are written to solve these
smaller problems. Subroutines are then called to execute until the whole problem
is solved.
It is also possible for a subroutine to call itself one or many times. Provided there
is some safeguard against a subroutine calling itself forever, subroutines that call
themselves can be a powerful technique for decomposing certain problems.
Example: Searching
Imagine searching a house. The algorithm would split the problem into searching
the rooms and then split searching the rooms into searching different areas in the
room. Eventually the area being searched becomes small enough that it can be
checked in one step. There is then no need to subdivide any further.
Another example of a problem that can be solved with recursion is that of drawing
a curved line:
An algorithm chooses a point half way along the line. That splits the curved line
into a left part and a right part.
Splitting the curve has decomposed the original problem into two smaller
problems. One problem is drawing the left half of the curved line, the other
problem is drawing the right half.
That might not seem like much of an improvement in efficiency, but it can be, if we
further split each half of the curved line into two smaller problems, and so on.
By repeatedly subdividing the problem, the part of the curved line to draw
eventually becomes small enough that it fits in just one dot, one pixel on the
screen.
• A recursive subroutine to draw a curved line can call itself to draw the left
and the right halves.
• It can have a logic test that detects when the problem is a pixel or smaller
in size.
• When the problem has been reduced that far, the subroutine can draw that
dot rather than doing more subdividing.
• The combined result of all the dots form the curved line.
Fractals
The next example uses recursion to draw a fractal that is a fern leaf.
• The fractal drawing algorithm in the example below recurses to draw four
different parts.
• The four different choices make smaller distorted versions of the whole
pattern in four different places. In turn four smaller distorted versions are
made in each of those places.
• The details of the four distortions are held as numbers in list variables
called f1, f2, f3, and f4.
• Often recursive code has a parameter that sets how far to recurse. In this
fractal example this parameter is called 'level'. Each time the function
recurses it decreases the value of level. When level reaches zero the
algorithm plots a dot, and stops subdividing the problem further.
We can modify the shape of the fern by changing some parameters in the
recursion code.
If you reduce the 9 in draw_fern( 9, (0,0) ) to 3 the program will plot far fewer
points.
Increasing the ‘9’ even a little bit, will make the program take a lot longer to run.
If you change the 9 to 30 the program will take over a million years to complete
running.
Tip: To stop the program before it finishes, use the same technique as for the
infinite loop. Go to the shell window and on the menus click ‘Shell’, and then
‘Restart Shell’.
• If one of the decision boxes in a flowchart was labelled incorrectly, with the
‘Yes’ and ‘No’ in the wrong places, the algorithm would have an incorrect
output. We call this type of error a bug.
A crash is when the program stops working completely. Users can lose their data
as the result of a crash.
A logic error occurs when the program instruction is for an incorrect action. The
program appears to be syntactically correct, (i.e. written correctly) but the logic is
flawed so when it runs it doesn’t do what was expected. In other words, a program
may operate correctly but may not do what is required.
For example:
if test_tube_is_full :
pour_more_acid_into_it().
Syntax errors also known as parsing errors are detected immediately by Python
when you attempt to run a program. Syntax errors aren’t thought of as bugs,
since Python will prevent the program from running when it finds a syntax error.
There is a colon at the end of the line which is incorrect. Simply correct this error
by removing the colon and re-run the program.
Logic Errors
Logic errors are not always easy to find. Consider the logic in this program to
display an instruction to put a cake in an oven when the oven reaches the correct
temperature.
The logic is wrong . To correct we need to change the != (Not equal) symbol to
the == (Equals) symbol.
Consider the example below and see if you can correct the logic:
The logic test will work correctly for age inputs 14, 15, 16, 17 and 18 as the
program will correctly print “He’s a teenager” for each input.
But for Age inputs 13 and 19 it will print “He’s not a teenager”
1. Open Python.
2. Type the code above correctly to fix the bug, by changing the line of code
beginning with ‘if’.
3. Check your solution by running your edited program.
4. Test values for age such as 12, 13, 14, 18, 19 and 20 to see if you get the
expected output.
The following program has two syntax errors and one logic error.
A programmer might notice that their program has a logic error, or they might not.
It is important to detect logic errors. One way to do this systematically is by
testing.
Testing
Running a computer program using different inputs to find if there are logic errors.
In testing, the tester needs to know what the results should be. They may refer to
the requirements in a specification to check that the program is doing what it is
supposed to.
After fixing a bug the program will be tested again to make sure the bug really has
been fixed.
1.3.1: The program SHALL dim the screen if the computer has not been used for
one minute.
A corresponding plan for testing would include a step for testing that requirement.
The plan would stipulate leaving the program running for one minute and
confirming that the screen does go dim after that time. Each requirement should
have some corresponding tests.
In this example, if after one minute the program crashes, there is a bug in the
program. However, if nothing special happens after a minute, one could argue
that there is no bug.
Finding Bugs
When a program gives the wrong or unexpected results, or if the program crashes
unexpectedly with an error, it is not always obvious why that has happened.
When a program gives the wrong answer, it may not always be enough to just
look at the code to find the bug.
One way to find out more about the bug is to include some extra diagnostics in the
code. These could be additional print statements in the program to display the
values of variables at various points in the program. These extra print statements
show how the values were changing.
Debugging
Running a faulty program with extra diagnostic information to work out where the
mistakes in the code are, and then fix those mistakes.
Debugging may uncover the bug and also show when the bug first occurs.
Without debugging, it may not be clear where the problem code is.
Software may benefit from translation of the strings into other languages. Usually
programmers attempt to use the same source code, but make the code more
flexible so that it can use different strings for different languages as indicated by a
parameter.
Work on localisation may also draw attention to other related opportunities for
generalisation.
In the lesson on computational thinking recall that we saw that a solution to the
problem of running a musical festival could be generalised. Experience in running
a music festival could contribute to solving the more ambitious problem of running
a musical tour.
In looking for opportunities to improve a recipe program, small additions that, for
example, count calories, or add up nutritional information, could generalise the
recipe program and make it part of a larger computer program for health and
nutrition.
Presenting a Program
A word processing program saves an author from typing the same text out many
times as they work through different versions of a document. A word processing
program does little to help an author find the right words and find ideas for
characters and plot.
If the algorithms are new, creative, innovative, it may be possible to patent them
and so protect them from being copied.
If the program uses a proprietary file format, i.e. owned by the programmer of
his/her company, that stores data in a way that other programs can’t easily read,
that may inhibit other companies from making their own version.
In communicating the value of a program, highlight what is unique about it. Show
that the unique aspects are of value to end users. A valuable program is one that
saves the end user time and money. Where possible support your claims about
the value of a program with numbers.
2. A logic test was intended to test if variable c, d and e are in order with c smallest and
e largest. Which of the following has a logic error:
a. if (c<d) and (d<e) :
b. if (e>d) and (d>c) :
c. if (c#d) and (d#e) :
d. if (e<d) and (d<c) :
4. Debugging is:
a. Checking a program against its requirements to see if it does what it is
supposed to do.
b. Enhancing a program by adding new features.
c. Work done to track down the cause of a problem and fix it.
d. Enhancing a program by taking out features which aren’t needed anymore.
5. One of the initial requirement for a particular program is that it ask for and remember
your name. Which of the following would you expect to see in the code to help meet
that requirement?
a. A recursive function
b. An input() statement
c. A bug
d. Code to convert a string to an integer.
7. When describing the commercial value of a new program, the best way is:
a. Show as detailed a flowchart as possible to show how complex the program
is.
b. Describe the benefit to users and back it up with numerical data if you can.
c. Explain that the program is new, and therefore it must be of value.
d. Explain that it uses only well known, widely used, reliable algorithms.
1.1.4 Define the term code. 2.2 Computer 2.2.1 Define the 3.1 Steps in an
Distinguish between Languages programming Algorithm
source code, machine construct term
code. sequence. Outline the
purpose of sequencing
1.1.5 Understand the terms 2.3 Text About when designing
program description Code algorithms.
and specification.
2.2.2 Recognise possible 3.1 Steps in an
1.1.6 Recognise typical 2.4 Stages in methods for problem Algorithm
activities in the Developing a representation like: 3.2 Flowcharts
creation of a program: Program flowcharts,
analysis, design, pseudocode.
programming, testing,
enhancement. 2.2.3 Recognise flowchart 3.2 Flowcharts
symbols like:
1.1.7 Understand the 2.1 Precision start/stop, process,
difference between a of Language decision, input/output,
formal language and a connector, arrow.
natural language.
2.2.4 Outline the sequence 3.2 Flowcharts
2.1.1 Outline the typical 1.1 of operations 3.3
methods used in Computational represented by a Pseudocode
computational Thinking flowchart,
thinking: pseudocode.
decomposition, pattern
recognition, 2.2.5 Write an accurate 3.2 Flowcharts
abstraction, algorithm based on a 3.3
algorithms. description using a Pseudocode
technique like:
2.1.2 Use problem 1.1 flowchart,
decomposition to Computational pseudocode.
break down data, Thinking
processes, or a 2.2.6 Fix errors in an 3.4 Fixing
complex problem into algorithm like: missing Algorithms
smaller parts. program element,
incorrect sequence,
2.1.3 Identify patterns 1.1 incorrect decision
among small, Computational outcome.
decomposed Thinking
problems.
• Understand key concepts relating to computing and the typical activities involved in
creating a program.
• Understand and use computational thinking techniques like problem decomposition,
pattern recognition, abstraction and algorithms to analyse a problem and develop
solutions.
• Write, test and modify algorithms for a program using flowcharts and pseudocode.
• Understand key principles and terms associated with coding and the importance of
well-structured and documented code.
• Understand and use programming constructs like variables, data types, and logic in
a program.
• Improve efficiency and functionality by using iteration, conditional statements,
procedures and functions, as well as events and commands in a program.
• Test and debug a program and ensure it meets requirements before release.
Having reached this stage of your learning, you should now be ready to undertake an ECDL
certification test. For further information on taking this test, please contact your ECDL test
centre.
ECDL Malta
Flat 2, St John’s Flats,
Naxxar Road,
Birkirkara BKR9040
Email: info@ecdl.com.mt