[go: up one dir, main page]

0% found this document useful (0 votes)
439 views20 pages

2.2 Workbook 1

The document provides an overview of key concepts to be studied for the GCSE J277 Unit 2.2 Programming Fundamentals topic. It covers variables, data types, operators, control structures like sequence, selection and iteration, file handling, arrays, functions, and SQL. Example code is given to illustrate various concepts like arithmetic operators, Boolean logic, casting, and looping constructs. The goal is to study how to solve problems using these fundamental programming techniques.

Uploaded by

19subedarz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
439 views20 pages

2.2 Workbook 1

The document provides an overview of key concepts to be studied for the GCSE J277 Unit 2.2 Programming Fundamentals topic. It covers variables, data types, operators, control structures like sequence, selection and iteration, file handling, arrays, functions, and SQL. Example code is given to illustrate various concepts like arithmetic operators, Boolean logic, casting, and looping constructs. The goal is to study how to solve problems using these fundamental programming techniques.

Uploaded by

19subedarz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

GCSE J277 Unit 2.

2 | Programming fundamentals Craig’n’Dave

Name: Zain

By the end of this topic, you will have studied:


• The use of variables, constants, operators, inputs, outputs and assignments
• Using the three basic programming constructs 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, NOT
• The user of data types: integer, real, Boolean, character, 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 an equivalent when solving problems, including one- 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 can not change

Assignment: Setting the value stored in a variable or constant

Example annotated program: OCR reference language


Example annotated program: Python
//Program to calculate the VAT of an ex-VAT item.
#Program to calculate the VAT of an ex-VAT item.
const vat_rate = 0.2
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: £", (cost))
print("Ex-VAT price was: £","{:.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

forename = input("Enter forename: ")


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

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.")
case > 12: do
print("Too many characters.") username = input("Enter a chosen username: ")
default: until username.length < 4 or username.length > 12
print("Valid username chosen.")
endswitch

Not supported by all languages, this construct is an alternative to Not supported by all languages, this iteration is different because it
using ELSE IF or ELIF commands. will 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


+-*/^
Addition
Subtraction
Multiplication
Division
= equals to 9=9

Integer division operators in use


= assignment X=1 MOD DIV

> Greater than 2>1

< Less than 3<4 Boolean operators

Greater than or equal Boolean operators in use TRUE/FALSE


>= Age>=5
to
(18 > 12) OR (18 > 27) t
NOT(12 > 18) f
<= Less than or equal to Price<=6 ((14 = 14) OR (9 > 11)) AND (4 < 4) f
(NOT (5 <= 5)) f
((NOT(4 > 3)) AND (5 < 12)) OR (9 = 9) t
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: 1 The output for 13 / 5: 2.6

The output for 2 DIV 4: 0.5 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
for counter in range(0,101):
number”
print (counter) If number% 2==0
if counter == 25:
print("-----") Print(“number is even”)
Else:
(“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

float decimal Price=£2.88

boolean True or false Condition=false

string Letters and words hello

char Stores single letters a


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

Casting operations

Casting: Changing the data type

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”:

Return the length of a string: Print(len(username))

Return the string in uppercase: Print(upper(username))

Return the string in lowercase: Print(lower(username))

Return the fifth character of the string: Print(username(4))

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

Return the ASCII value of a character: Print(ord(“A”))

Return a character from its ASCII value: Print(chr(65))


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 to a file, overwriting


all the existing data.

Data can also 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 = open("users.txt", "a")

date = str(datetime.date.today())

text_file.write(date+"\n")

text_file.write(username+"\n")

text_file.close()
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave

Using records

Most languages let you define your own data structures in the form of records.

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 MULTIPLY 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 and 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 contry=“Germany”

SQL to output all the data for Spain using a


SELECT*FROM world WHERE country=“spain”
wildcard * for the fields:

SQL to output the names of all countries


SELECT country FROM world LIKE “A”
beginning with A:

SQL to output the names of all countries in


SELECT country FROM where area =“468”
Europe with an area of 468:

SQL to output the names of all countries in


SELECT country FROM world WHERE continent LIKE (America)
North or South America:

SQL to output the names of all countries


SELECT country FROM world WHERE population>(SELECT population FROM world WHERE country=Russia
with a population greater than Russia using
a nested SELECT statement:

SQL to output the names of all countries in


Select country FROM where gdp>SELECT gdp from world here country+UK)
Europe with a GDP greater than the United
Kingdom using a nested SELECT statement:
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 as row/column or column/row, providing you are consistent throughout the program.
Therefore, if world_database[2,1] = “Africa”, then:
To change the GDP of Algeria to 300000 would require the statement:
world_database[2,5] is: algiers
world_database[2,4] = “300000”

world_database[3,2] is: 468


To change the area of Albania to 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

01: def roll_a_dice():


#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 We can control the flow of a program by calling a function. If we


15: import random call a function, it executes, returns a value, and then resumes
the program where it was called.
16: print("This tool outputs the value of two dice")
17: output_throw()
The purpose of a procedure:

The procedures perform certain tasks in a particular order on the basis


of the given inputs. A procedure, on the other hand, would return the
control, but would not return any value to the calling function or the
code.
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

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 can be very useful in programming. There are many situations when you might want to use this, especially in
video game programming. Here are some more examples:

• Choosing the winner of a lottery


• Picking people to complete a survey

Assume that the following line of pseudocode produces a random whole number from 1–6:

x  random(1, 6)

Write the pseudocode for a program that throws a six-sided dice 100 times. An
array called roll[1..6] stores the total number of times each number is rolled. The
program should end by outputting how many times each number was rolled.

import random
count1=0
count2=0
count3=0
count4=0
count5=0
count6=0
dice=random.randint(1,7)
for i in range(10000):
if dice==1:
count1+=1
if dice==2:
count2+=1
if dice==3:
count3+=1
if dice==4:
count4+=1
GCSE J277 Unit 2.2 | Programming fundamentals Craig’n’Dave

Assessment Target: Overall grade:

Minimum expectations by the end of this unit


 Learn terms 152-199 from GCSE Level Key Terminology.
 Complete all 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 and action Student response


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

Reflection and Revision checklist


Confidence Clarification
 I can explain variables and constants and why I would use them.

 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: 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 one-dimensional arrays (or their equivalent – e.g., lists in Python) when solving problems.
 I can use two-dimensional 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:

You might also like