You are on page 1of 20

GCSE J277 Unit 2.

2 | Programming fundamentals Craig’n’Dave

Name: Mahmud Rahman

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: A named location in memory whose value can change. Constant: A named location in memory whose value cannot change.

Assignment: Setting the value stored in a variable or constant.

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: £","{:.2f}".format(cost)) print("Ex-VAT price was: £", (cost))


print("VAT is: £","{:.2f}".format(vat)) print("VAT is: £", (vat))
print("Total price is: £","{:.2f}".format(total)) print("Total price is: £", (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

forename = input("Enter forename: ")


surname = input("Enter surname: ")
for counter=1000 to 1003
userp1 = forename + surname
userp2 = str(counter)
userp1 = userp1.lower
print("Suggested username:",userp1 + userp2)
userp2 = "1000"
next counter
print("Suggested username:",userp1 + userp2)
username = input("Enter a chosen username: ")

Selection Iteration with a condition controlled loop

if username.length < 4 or username.length > 12


then username = ""
print("Invalid username.") while username.length < 4 or username.length > 12
else username = input("Enter a chosen username: ")
print("Valid username chosen.") endwhile
endif
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

switch username.length:
case < 4:
print("Too few characters.")
do
case > 12:
username = input("Enter a chosen username: ")
print("Too many characters.")
until username.length < 4 or username.length > 12
default:
print("Valid username chosen.")
endswitch

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
addition
Operator Description Example
subtraction
multiplication
== equals to 9 == 9
division
exponentiation
= assignment x=1
Integer division operators in use
MOD DIV
> greater than 2>1 Modulus (remainder)
Integer division

< less than 3<4 Boolean operators


TRUE/FALSE

greater than or equal


>= age >= 5 Boolean operators in use TRUE/FALSE
to
(18 > 12) OR (18 > 27) TRUE
NOT(12 > 18) FALSE
<= less than or equal to price <= 6
((14 = 14) OR (9 > 11)) AND (4 < 4) FALSE
(NOT (5 <= 5)) FALSE
((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: 3 The output for 6 MOD 2: 0 The output for 6 * 2: 12

The output for 10 DIV 3: 3 The output for 10 MOD 3: 1 The output for 10 / 3: 3.33…

The output for 8 DIV 7: 1 The output for 8 MOD 7: 1 The output for 10 / 3: 3.33…

The output for 13 DIV 5: 2 The output for 13 MOD 5: 3 The output for 13 / 5: 2.6

The output for 2 DIV 4: 0 The output for 2 MOD 4: 2 The output for 2 ^ 4: 16

Program to output ----- every 25 iterations: Function to return whether an input number is odd or even:

number = int(input(“Please enter a number:


for counter in range(0,101): “)
print (counter) if number % 2 == 0:
if counter == 25: print(“Number is even”)
print("-----") else:
print(“Number is odd”)
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

Real/Float A decimal number price = 1.50

Bool True or False condition = False

String Letters and words Message = “Hello”

Char Stores single letter x = ‘a’


GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave

Casting operations

Casting: Changing the data type of a piece of data or variable

Examples of casting: i = str(i) x = int(x)

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: £","{:.2f}".format(cost)) print("Ex-VAT price was: £", (cost))


print("VAT is: £","{:.2f}".format(vat)) print("VAT is: £", (vat))
print("Total price is: £","{:.2f}".format(total)) print("Total price is: £", (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: print(len(username))

To return the string in uppercase: print(upper(username))

To return the string in lowercase: print(lower(username))

To return the 5th character of the string: print(username[4])

Assuming that the variable char is assigned the value “A”:

To return the ASCII value of the character: print(ord(“A”))

To return the character from the ASCII print(chr(65))


value:
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave

Basic file handling operations: reading records from a file

username = input("Enter your username:")

if user == "":

end_of_file = True

user = text_file.readline().strip()

text_file.close()

end_of_file = True

end_of_file = False

if user == username:

while not end_of_file:

print("Last logged in on:",login_date)

text_file = open("users.txt", "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 username = input("Enter your username:")
existing data in a file.

Data can be appended (added to the import datetime


end) of an existing file.
text_file = open("users.txt", "a")
Data cannot be inserted into the middle
of a file.
date = str(datetime.date.today())

text_file.write(username+"\n")

text_file.write(date+"\n")

text_file.close()
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

student1.firstName = "Jeff"
student1.surname = "Williams"
student1.depositPaid = 36.0
endprocedure

We can’t use a single array data structure to store this data because:

There are multiple data types

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: SELECT population FROM world WHERE country=‘Germany’

SQL to output all the data for Spain using a


SELECT * FROM world WHERE country=‘Spain’
wildcard * for the fields:

SQL to output all the name of all countries


SELECT country FROM world LIKE ‘A%’
beginning with A.

SQL to output the name of all countries in


SELECT country FROM world WHERE area=‘468’
Europe with an area of 468.

SQL to output the name of all countries in


SELECT country FROM world WHERE continent LIKE (‘% America’)
North or South America.

SQL to output the name of all countries SELECT country FROM world WHERE population > (SELECT population FROM world WHERE
with a population greater than Russia using country='Russia')
a nested SELECT statement.

SQL to output the name of the countries in


Europe with a GDP greater than United SELECT country FROM world WHERE gdp > (SELECT gdp FROM world WHERE country=’United Kingdom’)
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] “34”

x = bingo_ticket[7,0] “75”

x = bingo_ticket[5,2] “59”

Setting the value in the index identified with a ? to 28: bingo_ticket[2,1] = “28”
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave

Arrays

Two dimensional arrays can also be used to emulate database tables, providing all data is stored as a string.

world_database Note how the programmer must


decide which data item each index is
index 0 1 2 3 4 5 representing.

0 Afghanistan Asia 652230 25500100 20364 Kabul Index 0 – Country


Index 1 – Continent
1 Albania Europe 27648 2821977 12044 Tirana Index 2 – Area
Index 3 – Population
Index 4 – GDP
2 Algeria Africa 2381741 38700000 207021 Algiers Index 5 - Capital

3 Andorra Europe 468 76098 3222 Andorra la Vella

It doesn’t matter whether you visualise the indexes being [row, column] or [column, row] providing you are consistent throughout the program.
Therefore, if world_database[2,1] = “Africa”, then:

world_database[2,5] is: “Algiers” To change the GDP of Algeria to be 300000 would require the statement:

world_database[2,0] = “300000”
world_database[3,2] is: “468”

To change the area of Albania to be 28748 would require the statement:


world_database[1,1] is: “Europe”
world_database[1,2] = “28748”
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 random.randint(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)
14: print("The value of the roll is:",roll) The purpose of a function:

#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

Sub programs (functions and procedures) to produce structured code

#Data from weather station


Rainfall = [3.7, 2.3, 0, 0, 1.1]
TypicalWeek = 0.9

#Returns the average rainfall from 5 school days in a week


def AveRain():
Total = 0
for Measurement in Rainfall:
Total = Total + Measurement
Average = Total / len(Rainfall)
return Average

#Returns whether it rained on a day 1 = Monday


def RainDay(Day):
Days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
if Rainfall[Days.index(Day)] > 0:
print("It rained on",Day)
else:
print("No rain on", Day)

#Compares the week to a typical week for the month


def CompareWeek():
if AveRain() > TypicalWeek:
print("More rain than average this week.")
else:
print("Less rain than average this week.")

RainDay("Tuesday")
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:

Choosing the winner of a lottery


Picking people to complete a survey

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:

You might also like