Please enable JavaScript.
Coggle requires JavaScript to display documents.
A level. Programming concepts - Coggle Diagram
A level. Programming concepts
Data Type and related functions
Boolean
Used to store any typle of data where there are 2 possible values
True or False/ 1 or 0
/yes or no
example
Lesson options
Use of Boolean operations with increasing complexity
Using Boolean flags in while loops
While not done
Code Example
Make sure there is some sort of exit condition on infinite loop so you can quit it.
named after George Boole
discovered principles behind logic statements
Resources
What is a Bool
https://www.youtube.com/watch?v=iDaY0EntzJ4&list=PL0nQ4vmdWaA3GLsZESEkBiIAEvnDEge8D&index=8
https://www.youtube.com/watch?v=9OK32jb_TdI&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=8
Boolean operations
NOT
the inverse operator
If True goes in False comes out
If 1 goes in 0 comes out
In Boolean Algebra we write a NOT symbol by placing a bar on top of a letter (¯𝑨) or letters (¯(𝑪+𝑩))
Not Logic Gate
truth table
AND (& NAND)
AND
And Logic gate
In Boolean Algebra we write an AND symbol by placing a bullet point between two (A.B) or more (A. B.C) values.
AND Gate both inputs must be on / True
NAND
Logic gate
AND Gate combine with a NOT gate (Inverts the output of the AND Gate)
OR (& NOR)
OR
OR Gate Truth Table
OR Gate – Either one or both inputs must be True / on
In Boolean Algebra we write an OR symbol by placing a plus symbol between two (A+B) or more (A+B+C) values.
NOR
NOR Gate – Inverse of OR Gate
NOR
XOR
XOR Gate – eXclusive OR Gate Only one or the other True / on
In Boolean Algebra we write an XOR symbol by placing a plus symbol surrounded by a circle between two (A⊕B) or more (A ⊕B ⊕C) values.
Logic gate diagrams
https://www.youtube.com/watch?v=gI-qXk7XojA&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=10
Illustrated as a venn diagram
Text
String
Lesson options
Concatenating strings
‘Pretty printing’ strings
Displaying strings as a list of chars
Can link to Strings
Can multiply if logically consistent
A set of characters “Hello”, “World” etc (has speech marks)
e.g. name
e.g. address
e.g. phone number
any leading 0 would be removed if stored as a number
e.g. house number
Resources
What is a string
https://www.youtube.com/watch?v=df-LtiA95Uo&list=PL0nQ4vmdWaA3GLsZESEkBiIAEvnDEge8D&index=8
Python Strings Video Programiz
https://www.youtube.com/watch?v=Ctqi5Y4X-jA&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=5
https://www.youtube.com/watch?v=afRXifi57ws&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=6
String-handling operations
Strings can be thought of as arrays (lists) of characters
“Hello”
Index values
Length
All programming languages have a function that returns the length of a string or an array (normally the identical function)
In Python the function is len() which returns the number of characters in the string
space and punctuation count
code example
e.g. range(len
e.g. if X > len.....
Position
Position describes a subroutine to return the index value of a specific character or substring in a string
There are inbuilt functions in most languages for this
In Python the string method index() returns the index value of the start of a char or substring
Example
In the case of index if the substring isn’t found it raises an exception error – this can be handled using exception handling
Variable=InStr(string variable, "Words being searched for")
Then searches for the the "" phase by looking in the named string variable
returns starting index
Substring
Slicing... conjoined twins into 2 = 2 children
return a substring or part of a string
Example
Checking a sting for vowels
find() ... a substring
returns the index value if the substring is found and -1 if the substring is not found
Example
count()
returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.count(sub, start = 0,end = len(string))
sub − This is the substring to be searched.
start − Search starts from this index. First character starts from 0 index. By default search starts from 0 index.
end − Search ends from this index. First character starts from 0 index. By default search ends at the last index.
Code
Line 1 str = "this is string example....wow!!!"
Line 2: sub = 'i'
Line 3: print ("str.count('i') : ", str.count(sub))
variableName = str.Substring(X, Y)
Concatenation
We can concatenate strings using the + operator to build up strings from substrings
Example
Character code
Character → character code
Character code → Character
ord() converts a character to its ordinate or ASCII value
Ord
chr() converts a character from its ordinal value back to a char
Example
ASCII
American standard code for information interchange
7 bits to store characters
128 possible characters stored
Upper case
Lower case
Punctuation
Each character assigned a unique binary number
English only
Work on the ASCII standard began in May 1961,
Type Casting
string to integer
Example
string to float
Example
Commonly used to typecast a string value to an numeric value (integer or float)
This is most effective when combined with exception handling in case the value can’t be converted
Need to convert float and integer to string to concatenate strings
str()
Example
{}.format()
In Python 3.x we can also use the string format() method to atomically type cast a data type to a string
Example
list of functions
table list
https://www.youtube.com/watch?v=ALvbltAPOcI
check first principles
Character
A single character (normally a letter of the alphabet)
Based on the computer's defined character set
Resources
What is a char
https://www.youtube.com/watch?v=EWt5DGnPnlg&list=PL0nQ4vmdWaA3GLsZESEkBiIAEvnDEge8D&index=9
https://www.youtube.com/watch?v=_IERzjk4VQY&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=7
1 byte per character
Python doesn't support
in "" or ''
alphanumeric
letters
numbers
implemented as an array of bytes
Date/Time
Normally a complex datatype or a class object. Returns year, month, day (for date) and / or hour, minute, second, microsecond (for time). May also be a combined date / time object
30.04.2014
12:30
can add 5 to increase date by 5 days if declared as a date
complex data type
Code example
example. Today date. Full time and date.
interactive examples
https://www.w3schools.com/python/python_datetime.asp
In Python we use the datetime library to return the current time
The method strftime() formats the string into your preferred date (or time) format
Example
String to date/time
The method strptime() will convert relevant string values into a date time object
Example
%d = Date
%b = short format month name
%y year without centaury range
The method datetime() will convert relevant string to int values into a date time object
Example
https://www.youtube.com/watch?v=eirjjyP2qcQ&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM&index=19
Video: Python datetime - Work with Dates and Times
https://www.programiz.com/python-programming/datetime
Python libraries
https://docs.python.org/3/library/datetime.html
records
Complex data Structures
Can be composed of a variety of other data types logically linked together
Work like a suitcase. Can hold multiple items
0 based - like an lift. Ground floor = 0
https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/python-lists
Tuples
Basic Tuple code example
The variable coordinate equates to a tuple (stores both values)
python supported
returning a tuple from a subroutine
Code example
Not very useful. But good example
Can return really long tuples if handles correctly
Named tuples
Code example
Useful example
Line 8 - whole tuple
line 10 - only prints out the x value using .x (ref back to line 4)
Need to get students to practice
Rarely covered in GCSE
Can pass a tuple to a subroutine
() Normal brackets
Resources
Video: Python Lists and Tuples. 00:00 - 14:36 ](
https://www.programiz.com/python-programming/list
)
Dictionary
Code example
Better example of the 2 lists. Each name set up as a "key" with the score associated
i = key
j = score
Dictionary items have keys which are string values and the key is associated with a second data type
Dictionaries are quite complex data types and should be used when pupils are very confident with using lists!
Find more useful than name tuples
{ } curly brackets
Reosources
Video: Python Dictionaries to Store key/value Pairs
useful for students projects. Essential for A level
e.g. issue with separate lists doesn't link the data together. This is not ok at A level
Example
record = 1 line of a text file
arrays
1D array
A static array is one of a fixed size in memory
Code example
However arrays in pseudocode may start at 1 (this would be explicit in the definition)
acts like a constant
Dynamic Array
Memory allocated can change throughout program
adding data to array
The Python code above declares (or initialises) an empty list. It then dynamically adds items to the empty list using the command append
append to array code
appends 0,1,2 to the new list
Starts blank
In other languages you may have to specifically request the data
replacing data in array
Replace data in array
overwriting as already have the memory requested
2D array
Lists can be n dimensional e.g. a list of lists
2D lists are used frequently to store grids or matrices
Code example
3 lists within the list (list of list of 3 integers)
each list separated by ,
"Row" meaningful variable. Helps students understand what's happening
print (col, end="")
removes the automatic new line
noughts and crosses
Exam boards like testing these in exams
need to create/access/print/edit elements
Lists of items (normally of the same type) – may also be a list of complex data structures (dictionaries/tuples etc) or a list of lists!
e.g. class register of name
each name = element/member
[ ] Square brackets
The first item in an array generally has an index (the number indicating its position in the list) of 0
index array
Will be using frequently
Resources
What is an array
https://www.youtube.com/watch?v=21L4j8i3Tmw&list=PL0nQ4vmdWaA3GLsZESEkBiIAEvnDEge8D&index=11
Video: Python Lists and Tuples. 00:00 - 14:36
Difference between an array and a list
List = Mixed data types
Array = all one data type
Define and use user-defined data types based on language-defined (built-in) data types
This can be undertaken as an in class exercise
Throughout A Level Computer Science it is important that students program as much as possible
Use a named tuple or dictionary to store a set of data about students in a class (first name, last name, gender, age etc)
e.g. school register
Store the information in a dynamic list or array
Save the data to a CSV file
comma seperated value
python has librairies
Also can be used with excel and other database programs
Read the data back from a CSV file and store it in the same array / tuple or dictionary list
One option is to consider a scenario to code that requires or would benefit from a language defined datatype.
define more complex data type
lists of lists of complex data types
The list of built in types varies from language to language
Can make own data types = User defined data types
combine existing data types together
when there isn't one available in the logic
increases efficiency
Types
Composite
Combine existing data types together
Record
collection of related items that may have the same data types
Array
indexed collection of items with the same data type
List
index selection of items that can have different data types
Set
infinite number of different values with no order.
Class
gives properties and methods of an object
non composite
doesn't ref another data type
Boolean
Enumerated data types
e.g. Data type ==> Months of the year
Call current month using this
call next month using this
Declare winter as boolean
implied order
Not strings
So can be compared
has to decalre data type. Then assign to variables before they can be used.
e.g. dates of the week. Declare weekend
Pointer Data Types
Reference a memory location
Type <pointer> = ^<Type name>
Pointer/reference
Program Languages don’t always support this but should be covered.
Contains an address in memory where a datatype is stored (not used in Python but is used in C etc)
e.g. c
e.g. c++
Might show in year 13 for other languages or top set
analogys
Think of memory as pigeon holes
Index in a book
treasure map
Visual example
Difficult to demo in Python but could be a good use of the Little Man Computer to talk about data storage and addressing
helps data storage concept
Def = a data item that identifies a particular element in a data structure. Normally the front or rear
format and content dependent on underlying computer architecture
Stored on the Heap (not the stack)
less organised
Much faster
The address of operator (&) stores the memory address.
The dereference operator (*) accesses the value.
Pigeon holes for memory all numbered.,
Memory starts at lowest number and works up.
increment pointer to navigate
Code:
Example
A data type allows a program to determine the kind of operations that can be carried out on that data and additionally how much memory will be needed to store the data
Python loosely type
Don't need to specify data type of variable
Strongly typed variable
Variable data type needs to be defined.
practice in NEA format early on in the course
Definitions
Memory address =a specific location in memory where instructions or data are stored
Will be millions of them
Example ](
https://www.pinterest.co.uk/pin/364158319878250630/
)
Assignment = the process of giving a value to a variable or constant
Data type
determines what sort of data are being stored and how it will be handled by the program
Resources
AQA A level text book
Youtube channel - Jabrils
What are Data types? (introduction high level). Good revision from GCSE
https://www.youtube.com/watch?v=A37-3lflh8I
Programiz.com
Python Numbers, Type Conversion and Mathematics
https://www.programiz.com/python-programming/numbers
https://www.youtube.com/watch?v=KrToaEvDzdk&list=PLrK2OXXlOVH13aJmWlzA93DBbb_Rn5LvM
Type () to discover data type
table to list options
Example to ID different data type
Pokemon GO
Numbers
Integer
2-4 bytes per
range depends on how much memory is allocated
1/2 lesson
Any positive or negative whole number including 0 e.g. 1,2,-5 etc
e.g. score
e.g. pupils in a class
e.g. cars sold
real/float
A number with a decimal part e.g. 1.5, 6.0, 9.2
e.g. miles
e.g. kg
e.g. height
Lesson Options
Some basic mathematical operations including division or using the math library for sqrt() etc to generate more complex floats
naming depends on exam board
Resources
What is a float
https://www.youtube.com/watch?v=3htasDh_Uwc&list=PL0nQ4vmdWaA3GLsZESEkBiIAEvnDEge8D&index=10
if you multiple by a float - it will return a float
useful is more accurate answer required
won't store unit
4-8 bytes
Arithmetic operations
division result will always be a float
Can cause conceptual problems
Maths operators and python signs
DIV = Division of integers
Answer = A DIV B
Will give quotient and remainder similtaneously
Basic Expressions in code
all return integers but division always returns a float (even if the answer is a whole number)
Integer Division, including remainders (Quotient & Modulus)
Mod and Floor div code example
[
Revision poster
BBC Bitesize Worked examples
Relational operators table
Rounding
example
Round(div, decimal places)
Exponentiation
Exponentiation
Truncation
example
turning to string and using a string function to slice
Multiple ways to do it
Some students may not have done GCSE. So teach from first principles
But they may well be taking maths
Needs to be very confident coders in A levels
collection of programming examples to use for examples
Variable and Constant declaration
Naming
Use meaningful identifier names and know why it is important
so you know what it's for
so others know what its for
syntax
variable_name
camelCase
data type
score_int
https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/variables-expressions-and-statements
Assignment
Variables and Constants both act as storage locations (in primary memory)
Box example
filing cabinent
Jar
think of multiple one
try with physical props
Assignment is assigning a value to the memory location
Score example
variable value 0 assigned to score
<-- = assigned
Needs to happen before the constant or Variable be be used to check condition of constant/variable
gives a value to variable/constant
define the data the program will be using
Constant
To change the value of a constant, you have to change it in the source code and then recompile
A constant should not be the target of an assignment in the program (Python is loosely typed and constants and variables are not strictly defined. In other languages this is not the case)
python = CONSTANT for constant name
other languages have to say constant
E.G. C
Constants reduce the risk of errors by reducing access to memory location
fixed access
By using a constant for key values you only need to change the value once and the change is replicated throughout the code
Constant example in python
python 3
e.g. conversion rates
important that the name is self explanatory
easier to follow code as the program gets larger
good for debugging
easier when multiple programmers
quicker to update larer
Variable
The value of a variable can be changed while the program is running
Fixed value
variable that is given a value that then does not change for a duration of a loop
This might be an upper or lower bounds that the array is tending towards
working as a constant
stepper
variable used to move through an array or other data structure, often heading towards a fixed value and stepping through elements in an array
Stepping through the values in an array, or outputting a certain number of lines of text
e.g. for loop
count = loop
Most recent holder
variable used to record the last thing inserted by a user or the latest value being read from an array
input = console.readline() or getting the next value from an array
most wanted holder
variable that keeps track of the lowest or highest value in a set of inputs
calculating the top scorer in a football team, the lowest score in an exam and the highest number of pied wag tails seen by a bird watcher in a particular year
Gatherer
variable that accumulates or tallies up set of data and inputs. It is very useful for calculating totals or totals that will be used to calculate averages.
the total of ages of students in a class, the scores or batsmen in a cricket game, tally UMS points for an A-Level student or tell you the combined price of all the objects in your shopping basket
Question example: ID a variable that's functioning as a gatherier
temp
Transformation
used to store the result of a calculation involving more than one variable
transformation variables are used to calculate such things as compound interest
Followerer
used to keep check of a previous value of a variable, so that a new value can be compared
followers are often used when sorting arrays, in routines such as bubble or insertion sort
Temporary
A variable used for storing something for a very short period of time
temporary variables are often used for swapping values between other variables
examples
score
time
password
https://www.youtube.com/watch?v=cQT33yu9pY8
Global and Local variable
Global Scope Variables
Declared at the start of the program
they can be used in any procedure or subroutine in the program
Example
Disadvantages
Cause bugs
Waste memory
will continue to use memory whilst a program is running even if you no longer need/use it.
Can be hard to follow when tracing code
can call a global variable within a subroutine
global <variable name> = <Value>
This will then be impacted by the value of the global variable.
Local Scope Variable
they can only be used within the subroutine or program block they were declared in
Advantages
initiated within a limited scope
they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released.
cannot change a value accidentally that is being used somewhere else in the program
can use same variable name in multiple subroutines and they program doesn't confuse them
Example
"counter" inside the subroutine is local.
global "counter" doesn't change
If you pass a parameter into a subroutine the value that is changed is still local to that subroutine
Need to assign the value received from function to a variable
Otherwise "lost"
Example
applies if program spilt into subroutines and functions
https://www.youtube.com/watch?v=ngCDTEWVjrQ
https://www.youtube.com/watch?v=E5US2n_EWcI
https://www.youtube.com/watch?v=G8eO4qpOfm8
Declaration = the process of defining variables and constants in terms of their name and data type
Syntax
The structure of a programming language
(i.e. the use of colons and indents in Python)
c language
classes need curly brackets
Examples
common type of error
The rules of how words are used within a given language
https://www.youtube.com/watch?v=AGnECmJFA9U
Subroutine
procedures
Doesn't return a value
Example
Example 2
functions
Return a value
Return vowels
Can be very addictive once you get started.....
This needs to be done by students ( in GCSE you can get away without using them)
Will cause issues in year 13 if they don't understand in year 12.
Advantages
understand the code
Support and promote reuse of code by organising code into discrete algorithms
Increase the clarity and readability of the code
debug
Can then just test the function
work with multiple programmers
each can take a different subroutine
Support abstraction in that programmers can call subroutines and use them without necessarily knowing the underlying code within that subroutine
Local variables within the subroutine take less memory as local variable
Make code significantly more efficient in terms of removing the need to repeat sections of code
Coding subroutines
They need an identifier that usually indicates the what the subroutine does
Subroutines must be ‘called’ in code in order for them to be used
Just ignores the def. Needs to be called to do something
They are generally declared at the top of a block of code
It is possible to write subroutines inside a block of code but this is seen as a poor coding standard and makes the code harder to maintain
In Python subroutines start with def
Example
Example 2
Comments to help with identifying what's happening
A self contained algorithm which normally handles a specific event
clearer to debug
Code tends to be organised into subroutines logically
Parameters & Arguments
Parameter is the variable passed into the subroutine
generally data types / structures
Subroutines don’t have to take parameters but they do need to be defined with brackets
Example
Argument is the value of the parameter
Argument example]
Argument is the data that is passed into the subroutine
str1 is the parameter
Use camel casing for memory
Subroutines must be ‘called’ for them to be processed
Subroutines start with def in Python & they need an identifier (the subroutine name)
comp function and procedure
Stack frame
Used to retain and store data from local variables whilst other subroutines are called if the current subroutine has not finished its execution
Was more of a problem in older computers with limited RAM
Python manages the memory better. So memory issues minimised
e.g. dynamic filing cabinet
Code Example that uses a Stack Frame
The program calls the subroutine PlayGame() which in turn calls the subroutine CheckInt() which performs exception handling
the computer needs to remember how to return to PlayGame() once it has successfully executed CheckInt()
AQA style Example
Role of stack frame in subroutines
Creates a stack frame every time it gets called to another subroutine or function.
Stores for each Subroutine
the return address; this is the point it should go back to when it is done with the call
local variables; these are the variables in the current subroutine/function that it should restore
parameters; the data that is passed to the function/subroutine
Once it is done with the call, it removes that frame from the stack and looks at the return address of the next frame (which would belong to the function that called it) and resumes executing at that point.
This goes on until the stack is empty (i.e., it returns to the first subroutine in the program) and the program finishes.
Recursion
Diagram how stacks work with recursive
illustrates how the factorial program data is stored
trace table easier
get students to fill in
use print statements in code
Think of as pile of plates
Use to practically show in class
Recursive Techniques
A programming technique where a function calls itself inside itself
Code Example
Trace Table
The function must have an exit condition otherwise it gets stuck in an infinite loop
Advantages
Recursion can produce simpler, more natural solutions to a problem
Disadvantages
Can be more difficult to program
Recursion takes up large amounts of computer resources storing return addresses and the state of the variables stored
Factorial
PseudocodeExample
Ask students to get them thinking about how the students would program this
Recursive Python example
Non recursive Factorial Python
Pseudocode
Fibonacci Series
Values
Works like a iist/array
Pseudocode to return fib value at specific index
In Python
Trace Table
Code calls itself twice
At A level students need to be able to program with them
Use lots of comments
Use lots of print statements to error check
Works well with mathematical problems
E.g. Infinity Mirror is a literal example
e.g merge sort
ideally code
need to read
need to be able to follow and comment
Sequence/ Selection / Loops
Sequencing
The concept of a program executing in the programmed order to attain a specific output or function
program working in a set order
sequence depends on syntax of the programming language
Can use GCSE examples
https://www.youtube.com/watch?v=v_Pc3UnePZY
could use science/physics /maths
show them a jumbled up code and ask to reorganise
if anything in wrong order, it will not execute correctly
e.g. the macarana
to create more complex code you will need to plan ahead to work out how they will fit together.
Resources
https://www.youtube.com/watch?v=eSYeHlwDCNA
https://www.youtube.com/watch?v=VuQAyz-6yUs&list=PLCiOXwirraUDUYF_qDYcZV8Hce8dsE_Ho&index=2
iteration
Use definite and indefinite iteration, including indefinite iteration with the condition(s) at the start or the end of the iterative structure, (Top Exit and Bottom Exit loops).
Definite iteration
FOR Loop - Checks at the top of the loop
Python example- loops for a fixed / specified amount of time
return values 0, 9
can be nested
https://www.youtube.com/watch?v=O60CFmcWyEY
repeated in a process a certain number of times
then moved onto the next instruction
real life example
swim 10 lengths and then get out of the pool
https://www.youtube.com/watch?v=6iF8Xb7Z3wQ
Indefinite iteration
loops until a condition is met
While loop
The ‘check’ condition changes for the while as we check at the start of the sequence
checks condition at the top of the sequence – loop (iteration) completes when the condition is met
If never met, then will never enter
Example
use for selection
has exit condition
counter for visitors
Example 2
could write as white done ==False to make it easier for less confident students
Can nest while loops
Loops within a loop
Will loop until the inner condition is met and then checks the outer condition
Checks at the top of each loop
Nesting while loops
show as psuedocode/ flowcharts and coding
Repeat loop
checks condition at the bottom of the sequence – loop (iteration) completes when the condition is met
NB. Python does not have a repeat loop
Example
May see in pseudocode or flowchart. Won't need to program
real life example
reverse car until parking sensor beeps due to an obstacle
Make sure students familiar with trace tables
repeat a process of program
loop
selection
Comparing values and deciding on an action based on that comparison
Example
Compare strings
Can use GCSE examples to introduce
Weather = what things you need
Numerical comparisons
Can't compare different data types
Result depends on whether answer is True or False
Nested
Performing a second or more deeply nested selection should the prior selection criteria be met
indented structure in Python
Example
not a good example of MOD
can use GCSE examples to introduce
Maths examples ok
If/ Else IF/ Else
The way the code is indented indicates the sequence of events
https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/more-conditional-structures
https://www.youtube.com/watch?v=f4KOjWS_KZs
Exception handling
A number of functions and methods will raise an exception error in Python
This will cause the code to crash unless the exception is handled
The code below shows an implementation of exception handling
Example
Example 2
Causes of exceptions
In the case of index if the substring isn’t found it raises an exception error – this can be handled using exception handling
Not typecasting to a string for a print statement
Not typecasting string to int for operation
https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/more-conditional-structures
Checks questions in order
Stops with Block as soon as a True is found
Try and except block surrounds dangerous bit of code that likely to throw an error
If try works, except is skipped
keep this only to the bit of code that might blow. Otherwise code after will be skipped
if try fails, the except statement is carried out
conditional statement
example
works like an insurance policy
https://realpython.com/python-exceptions/
Syllabus
AQA
Programming paradigms
Procedural-oriented programming
programmer specifies the steps that must be carried out in order to achieve a result
also known as Imperative Programming Languages
a language based on giving the computer a structured, ordered set of commands or subroutines to follow
Examples of procedural languages C, Pascal, FORTRAN, COBOL (Python can be coded as a procedural or object oriented language)
Top-down design approach
Break down a system to develop an increasingly detailed insight into the subsystems it is composed of
Each system broken down to basic elements
We can then use this information to design and plan a procedural program considering algorithms and subroutines which will satisfy the functionality of the base elements
Hierarchy chart
a diagram showing the design of a system from the top down
Sample A Level question (Hierarchy Chart)
A holiday tour business wants to create a new computer system. They offer 30 different tours every year, each of which can have up to 50 people on it. The tour company organises the travel and hotel arrangements and lays on a number of excursions. The company needs to organise tour guides to accompany its customers and manage all of the payments from customers and to suppliers.
a) Explain how you could use abstraction by generalisation or categorisation to break this problem down
The broad categories that this could be broken into are: customers; destinations; travel methods; excursions; suppliers; payments.
b) Produce a hierarchy chart to show how you could decompose this problem.
Example chart
might be asked to fill gaps
find past papers. common questioj
Advantages
Code complexity can be reduced using the concepts of divide and conquer / top down design strategies
It is easier to debug and update individual sections of code
Code sections and subroutines can be re-used many times, decreasing complexity, saving time and promoting robust code
It is relatively easy to construct in a manner that allows multiple programmers to work on different subroutines or libraries
It has a clear logical structure that can be easier to follow
e.g.
recipie
tea
Structure chart
Code example
Example of structure chart for the code
Links subroutines showing how the data flows between them
Iteration
Diagram
Selection
Diagram
Object-Orientated Programming (OOP)
What is Object Oriented Programming?
A way of programing and program design in which programmers define and use specific data types and objects but also define subroutines (methods) that belong to those objects
You might define a class of vehicle that has specific attributes (number of wheels, power source, size) and then have a number of methods associated with that object – SetNumWheels() GetNumWheels() etc
good for games
MIT website
find past paper example
Classes made from:
Attributes - things that the object stores data in, generally variables.
Instance variable
unique to each method
class variables
Shared with all methods within the class
to call need to use classname.classvariable
Methods - Functions and Procedures attached to an Object and allowing the object to perform actions
def name(self, para1, para2....):
self.variable = x+y
Labelled
A method is a subroutine (function or procedure) that is stored as a class attribute
e.g. GetWheels()
code
If we try and call the method in the code below this is not possible in Python because the method is unbound – it’s not bound to a specific instance of the class
example error causing code
The code sample below shows how we would instantiate a instance of the class using the variable car1 with an argument of 4 and then we can call the method GetWheels()
Example
Static methods are a special case of methods. It allows you to write code that belongs to a class but that doesn’t use the object itself
Static method code example
In the example above you can see ConvertKmToMph() as a helper method that is class related but would be of use to child classes
Why use?
Improves code readability, signifying that the method does not depend on state of the object itself
Reduces memory usage because Python doesn't have to instantiate a bound-method for each object instiantiated
Eliminates the use of self argument
Virtual Methods
The method is defined in the base class but can be overridden by the method in the sub-class where it will used.
This is one of the instances that students need to be aware of that isn’t so explicitly defined in Python.
The example is taken from the interface declaration in the Delphi skeleton code from AQA
skeleton code example
Here is the same code in Python (MakeMove() was a virtual method in Delphi)
Python version
java handy example
Abstract methods
The actual method is not supplied in the base class, which means it must be provided in the sub-class
Code example python
makes more sense practically coding
Public, private and protected specifiers
Public attributes and methods
these can be accessed via the object
Protected attributes and methods
not supported in Python
Delphi example
Code
Any class/function may access the method/property
Private attributes and methods
these can only be accessed by attributes and methods with the object. This protects them from being changed directly externally (double underscore in Python)
Private attributes should only be accessible to change via the methods in a class
Methods to access private attributes are generally known as ‘Getters’ and ‘Setters’
‘Getters’ will either return a value via a function or display its value
Setters’ are used to ‘set’ / update the private attribute value
This serves to limit the actions that a user can perform with this variable attribute
Only this class may access the method/property. It won't even be inherited.
init
(self)
Example
public method sets the private attribute
shows how public and private to code
Protected
Only this class and any subclasses may access the method/property.
Class Diagrams
Breakdown
almost always in exam
https://www.youtube.com/watch?v=ZDa-Z5JzLYM
https://www.youtube.com/watch?v=BJ-VvGyQxho
Look at past papers
skeleton code
Encapsulation
a process of ‘binding’ data members (variables, properties) and member functions (methods) into a single unit e.g. into a class
Methods & attributes may be public or private – this can protect certain methods and attributes
Public attributes and methods - these can be accessed via the object
Private attributes and methods - these can only be accessed by attributes and methods with the object. This protects them from being changed directly externally
easier to understand by reading code
management tech
need to understand and recognise
find examples
what varies
everything that varies should be put into its own class (bicycles, cars, trucks)
You create a class for each unique set of properties and methods
Inheritance
A new class can inherit the attributes and methods of a parent class
Inheritance makes creating new classes very quick and easy.
Allows for a modular approach to creating classes, where you might never use the base class at all, but only as a means of creating other child classes.
Rather than having to rewrite the same functionality for similar objects, OOP allows you to reuse attributes and methods from parent classes
Code example
Inheritance diagram
Diagram example
The actual method is not supplied in the base class, which means it must be provided in the sub-class
Code example 2
tend to call child rather than parent
Aggregation
an aggregate object is an object which contains other objects
Examples
Sometimes it is more abstract (e.g. university and students).
Sometimes a class refers to real-world physical objects (like a Car).
a Car class would contain Engine, Wheels, Cabin, Fuel objects
A company's staff
Visual
A way of creating new objects in OOP based on the way they are related
Composition Aggregation
One object is composed of two or more existing objects
Diamond shaped arrowhead denotes Managers and Employees cannot exist unless Workforce does
Visual
Association Aggregation
One object is composed of two or more existing objects but each object is not entirely dependent on the other object for its existence
Visual
Composition
new class is entirely composed of objects of existing classes
The class is therefore entirely dependent on those objects for its own existence
Favour composition over inheritance
Using aggregation is less prone to errors than inheritance - so one class is created from others rather than inheriting
Polymorphism
Allow you to change the function of attributes and methods when you are inheriting from a parent class
Code example
Means that a method inherited from a base class can be redefined and used in different ways depending on the subclass / child class that inherited it
Code example 2
Overriding
When a method in a subclass takes precedence over a method with the same name in a base class
When a subclass performs this redefinition it is known as overriding
Advantages
Libraries can be created to enable easy reuse of code
Changes are made within the object which means changes made are less likely to impact on other parts of the program
Inheritance means that code can be reused throughout the program
Allows a team of programmers to work independently on a module
Programs are written in modules - easy to amend
OOP provides a clear modular structure for programs which makes it good for defining abstract datatypes where implementation details are hidden and the unit has a clearly defined interface.
OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.
High content in Paper 1
More important than paper 1. Need to start teaching in AS
Program to interfaces not implementation
Programs are written based on the interface rather than the individual implementation of the class
The interface defines the methods to be used which are then applied when the classes are defined
For example .
a bank account class might have a method to apply interest or to check the balance. These would be required by any bank account class
An interface defines the methods to be used when a class is defined
try an use examples students would know
book
fiction
genre
Non fiction
subjects
games chacters
enemies
bank account
calc interest
types of accounts
balance
add money
withdrawal
https://youtu.be/SiBw7os-_zI
Random number generator
Coding
Coding 2
Complex example
Typical applications
Creating a range of test data
producing data to use in computer simulations
creating random events and movements in games
selecting a random sample from a dataset
Most start with a seed value, so not completely random
program generated random number usually called "Pseudo random numbers"