2.2 - Programming Fundamentals (Part 2)

String Manipulation

- Programs may have to modify, extract or analyse information from strings.
- Examples of string manipulation include:

Changing the case of a string

- To change the case of a string, use the lower() or upper() functions on a string.
- For example, with exampleString = "Hello", exampleString.lower() will return "hello".

Concatenation (con-cat-en-ation)

- To concatenate two strings, use the + operator.
- For example, "Hello " + "World" will return "Hello World". (Note the space within the "Hello " string.)

Extracting a substring

- Extracting a substring is different in OCR Exam Reference Language and Python.

OCR Exam Reference Language Python
exampleString = "Hello World"
exampleString.substring(0, 5) // "Hello"
exampleString.left(5) // "Hello"
exampleString.right(5) // "World"
exampleString = "Hello World"
exampleString[0:5] # "Hello"
exampleString[:5] # "Hello"
exampleString[5:] # "World"

ASCII conversion

- To convert a string to ASCII:

OCR Exam Reference Language Python
ASC("A") // 65
CHR(65) // A
ord("A") # 65
chr(65) # A

Getting the length of a string

- To get the length of a string:

OCR Exam Reference Language Python
exampleString = "Hello World"
exampleString.length // 11
exampleString = "Hello World"
len(exampleString) # 11

File Handling

- To handle (read, write and append) files you must first open the file, then read/write, then close the file.
- (you'll need to scroll sideways to see second half the table if it doesn't fit on the screen, you can do that with all tables but this is the first one that doesn't fit on a 1080p screen)

OCR Exam Reference Language Python
newFile("example.txt") // creates example.txt
file = open("example.txt") // opens example.txt

file.write("Hello World") // writes "Hello World" to example.txt
print(file.read()) // prints "Hello World" by first reading example.txt and then printing it

file.writeline("Line 1") // writes "Line 1" to example.txt at line 1
file.writeline("Line 2") // writes "Line 2" to example.txt at line 2
file.writeline("Line 4") // will still write "Line 4", but to line 3 (since no line 3 exists yet)

print(file.readline()) // prints "Line 1" by first reading example.txt and then printing it
print(file.readline()) // prints "Line 2"

file.close() // closes example.txt and frees up memory
file = open("example.txt", "w") # opens example.txt for writing, creates it if it doesn't exist
file.write("Hello World") # writes "Hello World" to example.txt
file.close() # closes example.txt and frees up memory

with open("example.txt", "r") as file: # opens example.txt for reading
    print(file.read()) # prints "Hello World"

file = open("example.txt", "a") # opens example.txt for appending, creates it if it doesn't exist
file.write("\nHello World") # appends "\nHello World" to example.txt (\n means newline)
file.close()

# readline and writeline are done the same way as OCR Reference Language
                            

Records to Store Data

- Sometimes you will need to store data in a record, for example, if you need to store the name and age of a person.

Databases

- A database is a collection of fields (one slot of data) and records (a collection of fields all for one thing), each record is a set of data stored in a particular format.
- Most of the time databases use 'tables' to store records.
- Databases are faster and more secure than simply using text files.

Text Files

- Text files can be used to store data but this is not recommended for large datasets due to having to parse them and issues with splitting text.

Arrays

- Arrays are useful when working with small amounts of data, for example, a list of names, or a list of numbers.
- Arrays are faster than having to parse text files, but slower than databases.
(covered in the next section)


SQL

- SQL (Structured Query Language) is a language used to interact with a DBMS.
- Pronounced "sequel", or "ess queue ell".
- SQL is used to manage and manipulate data stored in databases.
- It allows users to create, read, update, and delete data, commonly known as CRUD operations.
- SQL is a standard language supported by many database systems such as MySQL, PostgreSQL, SQLite, and Microsoft SQL Server (the intricacies of which are not important for GCSE).

Basic SQL Commands

There are several key SQL commands you should know (if you're doing last-minute revision don't worry about most, the top 3 are the most important):

Example SQL Queries

Here are some example queries to show how SQL works (using an example database):

Name Age Grade
Bob 18 90
Charlie 17 92
Alex 16 75
1. Selecting data:
SELECT * FROM students WHERE grade > 80;
-- This will retrieve all students who have a grade higher than 80.
    
2. Inserting data:
INSERT INTO students (name, age, grade) VALUES ('Alice', 16, 85);
-- This will add a new record for a student named Alice.
    
3. Updating data:
UPDATE students SET grade = 90 WHERE name = 'Alice';
-- This will update Alice's grade to 90.
    
4. Deleting data:
DELETE FROM students WHERE name = 'Alice';
-- This will remove Alice from the database.
        

Arrays

- Arrays let you store a collection of data in a single variable.
- They come in multiple 'dimensions', the most common being 1D and 2D.

1D Arrays

- A 1D array is a single dimension array, for example: array exampleArray = ["Hello", "World"].
- They are far more common than 2D arrays, and are used for storing data that does not require tables.

OCR Exam Reference Language Example

array emptyArray = [10] // You specify the size of the array
array exampleArray = ["Hello", "World", ""]
exampleArray[0] // "Hello"
exampleArray[1] // "World"

exampleArray[2] = "!" // Assigns "!" to the 3rd index

/* Loop through the array. This syntax isn't explicity defined 
in the OCR Exam Reference Language spec, but it should be fine. */
for item in exampleArray
    print(item) // prints "Hello", "World" and "!"
next item
            

Python Example

emptyArray = [] # You don't have to specify the size of the array
exampleArray = ["Hello", "World"]
exampleArray[0] # "Hello"
exampleArray[1] # "World"

exampleArray[2] = "!" # Assigns "!" to the 3rd index

# Loop through the array
for item in exampleArray:
    print(item) # prints "Hello", "World" and "!"
            

2D Arrays

- A 2D array is a two-dimensional array.
- They are used for storing data that requires tables to visualise.
- The right index can be thought of as the column, and the left index can be thought of as the row.

OCR Exam Reference Language Example

array emptyArray = [10, 10] 
array exampleArray = ["Hello", "World"], ["!", "?"]
exampleArray[0, 0] // "Hello"
exampleArray[0, 1] // "World"
exampleArray[1, 0] // "!"
exampleArray[1, 1] // "?"
            

Python Example

exampleArray = [["Hello", "World"], # multi-line not required,
                ["!", "?"]]         # but it's easier to read
exampleArray[0][0] # "Hello"
exampleArray[0][1] # "World"
exampleArray[1][0] # "!"
exampleArray[1][1] # "?"
            

Functions and Prodecures (Subroutines)

- Functions and Prodecures (also called subroutines) are a way to group together a set of instructions that can be called multiple times.
- They help decompose a problem to make it easier to undestand and are used to help duplicating code, improve maintainability and readability, and to perform calculations, retireve data, or make decisions.
- They can take paramaters, which are values that are passed into the function when it is called.
- Functions, but not prodecures, return values, this is done by assigning the return value to a variable.
- Functions can be called recursively, which means that a function can call itself.

OCR Exam Reference Language Python
function add(a, b)
    return a + b
endfunction

result = add(2, 3)
print(result) // 5

procedure add(a, b)
    print(a + b)
endprocedure

add(2, 3) // 5
                        
def add(a, b):
    return a + b

result = add(2, 3)
print(result) # 5

def add(a, b):
    print(a + b)

add(2, 3) # 5
                        

Local vs Global Variables

- Local variables are only available within the function or prodecure they are declared in.
- Global variables are available to all functions and prodecures.
- Variables outside functions and procedures are automatically global, but variables inside functions and prodecures have to be made global with the global keyword.

def add(a, b):
    sum = a + b # local
    global globalsum
    globalsum = sum
    return sum

add(2, 3)
print(globalsum) # 5
print(sum) # not defined error
        

Random Numbers

- Random numbers are used to simulate the randomness of the real world, for example, to simulate the outcome of a dice roll, or the number of people in a room.

OCR Exam Reference Language Example

random_number = random(1, 6)
print(random_number)
        

Python Example

import random

random_number = random.randint(1, 6)
print(random_number)