Algorithm Specification
There are three standard algorithms, or patterns, for National 5: running total, input validation and traversing an array.
Running Total
The running total in a loop algorithm (or running total) is used to keep a running total of some numbers, either:
Values entered by the user
A list of values in an array
The algorithm loops several times, takes in a value, and adds it to the total.
A running total usually uses a fixed loop. It could be a running total of integers or real numbers.
Running Total from user input
total = 0
for counter in range(0, 10):
num = (int(input("Enter number"))
total += num
Running Total from an Array
temps = [18.2, 19.1, 20.1, 19.8, 21.4]
total = 0.0
for counter in range(0, 5):
total += temps[counter]
Running Total with a Conditional Loop
total = 0
while total < 100:
num = (int(input("Enter number"))
total += num
Input Validation
This is the standard algorithm for making sure a user is entering the correct (or valid) information.
This example asks the user to enter their age, which must be at least 15 to use the rest of the program.
First, it asks the user to enter a valid age. It only triggers the while loop if their age is less than 15. If so, it shows an error message and asks them to re-enter the data.
# Ask the user for their age
age = int(input("Please enter a valid age"))
# This loop only triggers if their age is less than 15
while age < 15:
print("Sorry, you must be 15 or over")
age = int(input("Please enter a valid age"))
More Examples
Validating within a number range
valid = False
#get user to input a number and loop until number is between 0 and 120
while valid == False:
age = int(input("What age are you: "))
if age < 0 or age > 120:
print("Age invalid.")
print("Please enter an age between 0 and 120.")
else:
valid = True
print("Input is valid.")
Validating a string
password = "password1234"
while valid == False:
guess = input("Please enter the password: ")
#if input is incorrect, ask to try again
if guess != password:
print("Incorrect. Please try again.")
else:
valid = True
print("Access Granted.")
Traversing an Array
We can use a loop to traverse the array - that means, to travel through it, or loop through it.
This example sets up a list of seven names. It has a loop that counts 7 times (from 0 to 6). It prints one of the names each time, using the loop counter variable.
This prints the values of names[0], names[1], names[2] etc. all the way to names[6].
# An array of seven names
names = [“Dopey”, “Grumpy”, “Doc”, “Bashful”, “Sneezy”, “Sleepy”, “Happy”]
# The array elements are numbered from 0 to 6
# Loop from 0 to 6 and print the name
for counter in range(0, 7):
print(names[counter])