GCSE J277 Unit 2.
2 | Programming fundamentals Craig’n’Dave
Name:
Specification & learning objectives
By the end of this topic you will have studied:
• The use of variables, constants, operators, inputs, outputs and assignments
• The use of the three basic programming constructs used to control the flow of a program: Sequence, Selection, Iteration (count and condition-controlled loops)
• The common arithmetic operators
• The common Boolean operators AND, OR and NOT
• The user of data types: Integer, Real, Boolean, Character and string, Casting
• The use of basic string manipulation
• The use of basic file handling operations: Open, Read, Write, Close
• The use of records to store data
• The use of SQL to search for data
• The user of arrays (or equivalent) when solving problems, including both one-dimensional and two-dimensional arrays
• How to use sub programs (functions and procedures) to produce structured code
• Random number generation
We recommend the OCR endorsed text book from PG Online for use during your GCSE studies.
Craig'n'Dave videos for SLR 2.2
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Variables, constants, inputs, outputs and assignments
Variable: Constant:
Assignment:
Example annotated program: Python Example annotated program: OCR reference language
#Program to calculate the VAT of an ex-VAT item. //Program to calculate the VAT of an ex-VAT item.
vat_rate = 0.2 const vat_rate = 0.2
cost = input("Enter the ex-VAT price of the item: cost = input("Enter the ex-VAT price of the item:
£") £")
cost = float(cost) cost = float(cost)
vat = round(cost * vat_rate,2) vat = round(cost * vat_rate,2)
total = cost + vat total = cost + vat
print("Ex-VAT price was: print("Ex-VAT price was: £", (cost))
£","{:.2f}".format(cost)) print("VAT is: £", (vat))
print("VAT is: £","{:.2f}".format(vat)) print("Total price is: £", (total))
print("Total price is: £","{:.2f}".format(total))
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
The use of the three basic programming constructs: sequence,
selection and iteration
Sequence Iteration with a count controlled loop
Selection Iteration with a condition controlled loop
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
The use of the three basic programming constructs: sequence,
selection and iteration
Selection Iteration with a condition controlled loop
Not supported by all languages, this construct is an alternative to using Not supported by all languages, this iteration is different because it will
else if or elif commands. execute the code inside the loop at least once.
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Arithmetic, comparison and Boolean operators Basic arithmetic operators
+-*/^
Comparison operators
Operator Description Example
== equals to 9 == 9
Integer division operators in use
MOD DIV
Boolean operators
Boolean operators in use TRUE/FALSE
(18 > 12) OR (18 > 27)
NOT(12 > 18)
((14 == 14) OR (9 > 11)) AND (4 < 4)
(NOT (5 <= 5))
((NOT(4 > 3)) AND (5 < 12)) OR (9 == 9)
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Applying computing-related mathematics
The output for 6 DIV 2: The output for 6 MOD 2: The output for 6 * 2:
The output for 10 DIV 3: The output for 10 MOD 3: The output for 10 / 3:
The output for 8 DIV 7: The output for 8 MOD 7: The output for 10 / 3:
The output for 13 DIV 5: The output for 13 MOD 5: The output for 13 / 5:
The output for 2 DIV 4: The output for 2 MOD 4: The output for 2 ^ 4:
Program to output ----- every 25 iterations: Function to return whether an input number is odd or even:
for counter in range(0,101):
print (counter)
if counter == 25:
print("-----")
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Data types
Data Types
Data type Description Example assignment
Integer A whole number points = 20
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Casting operations
Casting:
Examples of casting:
Example annotated program: Python Example annotated program: OCR reference language
#Program to calculate the VAT of an ex-VAT item. //Program to calculate the VAT of an ex-VAT item.
vat_rate = 0.2 const vat_rate = 0.2
cost = input("Enter the ex-VAT price of the item: cost = input("Enter the ex-VAT price of the item:
£") £")
cost = float(cost) cost = float(cost)
vat = round(cost * vat_rate,2) vat = round(cost * vat_rate,2)
total = cost + vat total = cost + vat
print("Ex-VAT price was: print("Ex-VAT price was: £", (cost))
£","{:.2f}".format(cost)) print("VAT is: £", (vat))
print("VAT is: £","{:.2f}".format(vat)) print("Total price is: £", (total))
print("Total price is: £","{:.2f}".format(total))
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Basic string manipulation
Assuming that a string called username is assigned the value: “craigndave1000”:
To return the length of a string:
To return the string in uppercase:
To return the string in lowercase:
To return the 5th character of the string:
Assuming that the variable char is assigned the value “A”:
To return the ASCII value of the character:
To return the character from the ASCII
value:
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Basic file handling operations: reading records from a file
end_of_file = True
if user == "":
end_of_file = True
user = text_file.readline().strip()
text_file.close()
username = input("Enter your username:")
end_of_file = False
if user == username:
while not end_of_file:
print("Last logged in on:",login_date)
text_file = open("[Link]", "r")
print("User not found.")
login_date = text_file.readline().strip()
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Basic file handling operations: writing records to a file
Data can be written, overwriting all the text_file.write(username+"\n")
existing data in a file.
Data can be appended (added to the username = input("Enter your username:")
end) of an existing file.
import datetime
Data cannot be inserted into the middle
of a file.
text_file.close()
text_file = open("[Link]", "a")
text_file.write(date+"\n")
date = str([Link]())
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Use of records
Most languages let you define your own data structures in the form of records.
A complete example:
type Tstudent = record
firstName As String
surname As String
depositPaid As Double
datePaid As Date
end
procedure main()
student1 As TStudent
[Link] = "Jeff"
[Link] = "Williams"
[Link] = 36.0
endprocedure
We can’t use a single array data structure to store this data because:
Many programming languages allow you to store your record data in a database such as Access, MySQL etc. and access it in the program using SQL.
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
The use of records to store data & SQL to search for data
SQL commands: SELECT – which fields (* is a wildcard), FROM – which table, WHERE – criteria (LIKE used with % as a wildcard)
Assuming a database table called ‘world’ has a record structure of: country, continent, area, population, gdp, capital:
SQL to output the population of Germany:
SQL to output all the data for Spain using a
wildcard * for the fields:
SQL to output all the name of all countries
beginning with A.
SQL to output the name of all countries in
Europe with an area of 468.
SQL to output the name of all countries in
North or South America.
SQL to output the name of all countries
with a population greater than Russia using
a nested SELECT statement.
SQL to output the name of the countries in
Europe with a GDP greater than United
Kingdom using a nested SELECT statement.
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Arrays
A bingo ticket can be represented in memory using a two dimensional array.
bingo_ticket
index 0 1 2 3 4 5 6 7 8
0 5 49 63 75 80 All the data in an array must be of the same
data type. In this example all the data items
1 ? 34 52 66 77 are integers.
The size of an array is declared when the
2 6 11 59 69 82 program is written.
The array is zero-indexed. Assuming the indexes refer to the column followed by the row:
x = bingo_ticket[3,1]
x = bingo_ticket[7,0]
x = bingo_ticket[5,2]
Setting the value in the index identified with a ? to 28:
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Sub programs (functions and procedures) to produce structured code
Order of program
01: def roll_a_dice(): execution:
#Roll a dice
02: return [Link](1,6)
03: def order_dice(d1, d2):
#Change the order of the dice to highest value
first
#and join the values together
04: if d1>=d2:
05: return int(d1 + d2)
06: else:
07: return int(d2 + d1)
08: def output_throw():
#Output the results of the two dice thrown
09: dice1 = str(roll_a_dice())
10: dice2 = str(roll_a_dice())
11: print("Dice 1:",dice1)
12: print("Dice 2:",dice2)
13: roll = order_dice(dice1, dice2) The purpose of a function:
14: print("The value of the roll is:",roll)
#Main program
15: import random
16: print("This tool outputs the value of two dice")
17: output_throw() The purpose of a procedure:
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Random number generation
The ability to generate a random number in programming can be very useful. There are many situations when you might want to use this especially in
games programming, some examples are:
Assume the following line of pseudo-code produces a random whole number between 1 and 6:
x random(1, 6)
Write the pseudocode for a program which will throw a 6-sided die 100 times.
An array called roll[1..6] store the total number of times each number is rolled.
The program should end by outputting how many times each number was rolled.
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Assessment Target: Overall grade:
Minimum expectations by the end of this unit
You should have learnt terms 152-199 from your GCSE Level Key Terminology during this unit.
You have completed all the pages of the workbook
Score 80% in the end of unit test.
Feedback
Breadth Depth Understanding
All aspects complete Excellent level of depth All work is accurate
Most aspects complete Good level of depth Most work is accurate
Some aspects complete Basic level of depth shown Some work is accurate
Little work complete Little depth and detail provided Little work is accurate
Comment & action Student response
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave
Reflection & Revision checklist
Confidence Clarification
I can explain the use variables and constants and why I would use each.
I can explain what the various operators are.
I can explain how to input data to a program and write it out again.
I can explain the three basic programming constructs: sequence, selection, iteration (count and condition controlled).
I can carry out various basic string manipulation techniques.
I can use basic file handling operations in a program such as: open, read, write, close.
I can use records to store data.
I can use basic SQL commands to search for data in a database.
I can use 1-D arrays (or their equivalent e.g. lists in Python) when solving problems.
I can use 2-D arrays (or their equivalent e.g. lists in Python) when solving problems.
I can explain the difference between a procedure and a function.
I can explain why using sub programs is useful when producing a structured program.
I can explain the use of the following data types: integer, real, Boolean, character, string.
I can explain what casting is.
I can explain the common arithmetic operators.
I can explain the common Boolean operators.
My revision focus will need to be: