Computational Constructs
Parameter Passing
A parameter is a variable or value that is passed into and / or out of a subprogram.
There are two types of parameters: formal and actual.
Actual parameters are passed into a subprogram when it is called from another part of the program.
Formal parameters are used in the subprogram.
The program below has 3 different sets of data which all reuse the same subprogram.
#function to display info that is fed in to the module
def displayData(dataInput, message):
average = sum(dataInput) / len(dataInput)
print("Average " + message.lower(), round(average, 1))
print(message + "s ranged from:")
print(min(dataInput), "to", max(dataInput))
print()
#data set 1
scores = [4, 6, 8, 5, 6, 3, 5, 9, 10, 2, 4, 6, 3, 5]
title = "Score"
displayData(scores, title)
#data set 2
pHReadings = [3.4, 3.7, 3.0, 4.2, 5.0, 2.7, 3.2]
text = "pH"
displayData(pHReadings, text)
#data set 3
heights = [154, 158, 187, 172, 155, 190, 182]
word = "Height"
displayData(heights, word)
Global/Local Variables
Local variables
A variable declared within a sub-program.
Only recognised in the sub-program in which the variable is declared.
Can only be changed by code in the sub-program in which the variable is declared.
Global variables
A variable declared as global in the main program.
Can be recognised and changed by any code across the entire program.
Global variables are generally not good practice because
they can be changed by other modules using the same variable name, leading to logic errors.
they become difficult to manage when more than one programmer is working on the program code.
Variable scope
The scope of a global variable is the entire program.
The scope of a local variable is the sub-program in which it is declared.
Sub-Programs
Modular programs are broken down into blocks of code called sub-programs.
A sub-program (or subroutine) is an independent block of code within the main program.
Typically a sub-program carries out a specific task.
Sub-programs can be designed, programmed and tested independently of each other.
Different programmers can work on different sub-programs.
Each sub-program begins with a declaration which includes
the sub-program name
a list of formal parameters that are being passed into the sub-program
A sub-program can be either:
a function - returns a value
a procedure - produces an effect
Function Example
A function returns a single value.
Procedure Example
A procedure produces an effect.
Pre-Defined Functions
N5
Random
It returns an integer between the lower and upper parameters passed in.
import random
mynumber = random.randint(1, 6)
Length
The length function, shortened to len() returns the length - the number of characters - in a string.
how_long = len("hello")
print(how_long)
Round
Rounds either:
To the nearest integer (e.g. 3.141 becomes 3)
num1 = round(3.14159265)
print(num1)
To a certain number of decimal places (e.g. 3.141 rounded to 2 decimal places)
num1 = round(3.14159265, 2)
print(num1)
Floating Point > Integer
You can convert a floating-point number to an integer. It is also known as “truncating” the number.
This is not the same as rounding.
When a number is truncated, it effectively chops off the fractional part.
Both sections of code below would display 3.
num1 = int(3.14159265)
print(num1)
num1 = int(3.99999999)
print(num1)
Modulus
Most programming languages have a predefined function which calculates the modulus (the remainder of a division).
Substrings
You know already that a string is a collection of characters:
A substring is an extract of the string, between two points. In the example above, the substring is “Hello“.
A substring from 0 to 2 is “Hel”
A substring from 4 to 6 is “o w”
A substring from 6 to 9 is “worl”
There are interesting uses for a substring. We could:
Find the first character in a word or sentence
Extract one character at a time, e.g. to convert them to ASCII codes
Search for the position of a space between two words
We can extract (or slice) the substring with this syntax:
mystring = "Hello world"
sub1 = mystring[ marker1 : marker2 ]
This would return the first five characters (0 to 4): Hello.
mystring = "Hello world"
sub1 = mystring[0:4]
Substring allows us to work backwards. If we want the last character of the string, we could use -1 as a shortcut. This code returns ‘d’:
mystring = "Hello world"
sub4 = mystring[-1]
To find the last five characters, we would start at position -5 (5 from the end), and leave the second parameter blank. The variable sub5 would contain “rld”, and sub6 would contain “world”.
mystring = "Hello world"
sub5 = mystring[-3:]
sub6 = mystring[-5:]
ASCII > CHAR
You will recall from computer systems that every character (every letter, digit or symbol) can be represented by a number. They use a system of ASCII (7 or 8 bit) or Unicode (16 bit).
There are two functions that convert back and forth between ASCII codes and their associated characters.
To get an ASCII number from a character: ord(something)
To get a character from an ASCII number: chr(something)
# User enters A, this prints 65
mychar = input("Enter a character")
print(ord(mychar))
# User enters 65, this prints A
mynumber = int(input("Enter an ascii code"))
print(chr(mynumber))
File Handling
A computer program can use data that is:
assigned within the code
inputted by the user
held in an external file
A computer program can open, create, write to, read from and close an external file.
Opening A File
There is a three step process to using a file in your code:
Open a connection to the file
Read or write from the file, as desired
Close the file
The open() function opens the file. It takes two parameters - the name of the file (as a string), and the mode (in your case, either “r” for reading or “w” for writing). We close() the file when finished.
# Open the file for writing
highscores = open("scores.txt", "w")
# Close the file
highscores.close()
Writing to a File
To write data to a file, we use the w mode (w for writing).
Writing will create a file with that name if one does not already exist.
# Open the file for writing
messagefile = open("message.txt", "w")
# Save some data in the file
messagefile.write("Bla bla, this message will be saved in the file")
# Close the file
messagefile.close()
Note: this overwrites whatever was previously in the file!
Reading a Whole File
To read saved data from a file, we use the r mode (r for reading).
# Open the file for reading
scorefile = open("scores.txt", "r")
highscore = scorefile.read()
print(highscore)
# Close the file
scorefile.close()
Reading Line by Line
This method is used when you have a file with multiple lines, and you want to use each piece of data separately.
The initial process is the same, we open the file for reading.
Instead of read(), we use the readlines() function, which returns all the lines of the file in an array. So for this file, it would produce an array with 10 items, each of them containing a name.
This example would print the name "Matthew"
# Open the file for reading
namesfile = open("names.txt", "r")
# We have a list (array) called names
names = namesfile.readlines()
# We can print one of the names in the array
print(names[0])
# Close the file
namesfile.close()
This example would print the entire array, one at a time.
# Open the file for reading
namesfile = open("names.txt", "r")
# We have a list (array) called names
names = namesfile.readlines()
# Print all the lines, one at a time
for counter in range(0, 10):
print(names[counter])
# Close the file
namesfile.close()
CSV's
Comma-separated values (.csv) files are often used to store table-like data. Values are stored line-by-line, with one line for each row of data, and columns separated by commas.
Once we have read each line from the file, we split the line into its constituent parts.
We use the split() function to separate each line, passing as a parameter the character we want to split with (usually a comma). Based on the first row of the table above, the following code would print “1027”.
# Open the file for reading
schoolfile = open("Schools.txt", "r")
# Read in the data one line at a time
lines = schoolfile.readlines()
# Loop through the schools, one at a time
for counter in range(0, 3):
school = lines[counter]
parts = school.split(",")
name = parts[0]
town = parts[1]
# Close the file
schoolfile.close()
Reading into Parallel Arrays
# Parallel arrays for school data (set up with three blanks each)
schools = ["", "", ""]
towns = ["", "", ""]
pupil_count = [0, 0, 0]
# Open the file for reading
schoolfile = open("Schools.txt", "r")
# Read the file into an array of lines
lines = schoolfile.readlines()
# Loop through the array of lines
for index in range(0, 3):
parts = lines[index].split(",")
# Store in the parallel arrays
schools[index] = parts[0]
towns[index] = parts[1]
pupil_count[index] = parts[2]
# Close the file
schoolfile.close()
Reading into an Array of Records
from dataclasses import dataclass
# Define record structure
@dataclass
class car:
registration: str
make: str
model: str
mileage: int
# Create an array for 100 blank cars
cars = [car] * 100
# Read data from the file
file = open("vehicles.csv", "r")
lines = file.readlines()
file.close()
for i in range(0, 100):
parts = lines[i].split(",")
cars[i] = car(parts[0], parts[1], parts[2], int(parts[3]))
# Count how many have mileage over 25000
counter = 0
for i in range(0, 100):
if cars[i].mileage > 25000:
counter = counter + 1
# Show results
print("Cars with mileage over 25000:", counter)