Download presentation
Presentation is loading. Please wait.
1
Programming Constructs Notes
Software Design & Development: Computational Constructs, Data Types & Structures, Algorithm Specification
2
Contents Variables & Data Types Assignments & Arithmetic Operators
Questions Assignments & Arithmetic Operators Selection Fixed Loops Conditional Loops Input Validation Pre-defined Functions Contents page with links to lesson topics
3
Variables In a computer program, a variable is part of the computers memory that has been set aside to store a single item of information for the program The program can use the information stored in the variable to carry out calculations and display output 4
4
Variables should have meaningful names which tell you about what the information stored in them represents. Variables should also have data types which say how the computer is storing the information, and how it can be used in your program When you change the value inside a variable, the old value is lost forever 14 16 SET age TO 16 age integer age integer
5
Data Types Boolean variables have one of two values – either True or False The user can’t enter Boolean values as input easily in Python Strings are made up letters, symbols and numeric characters To ask the user to enter a string in python: name = input(“Enter your name: ”)
6
Integers are whole numbers
To ask the user to enter a integer in python: age = int(input(“Enter your age: ”)) Floating point numbers can have any value – whole numbers and the fractions in-between To ask the user to enter a floating point in python: height = float(input(“Enter your height: ”))
7
Arrays An array is a special type of data structure that can hold multiple values, using an index to identify each value Most programming languages make index [0] the first element in an array Arrays can be of any of the data types – an array of integers would hold multiple whole number values. For example: 14 17 12 7 age[0] integer[] age[1] integer[] age[2] integer[] age[3] integer[]
8
Questions – Variables and Data Types
Answer questions in full sentences! Describe the four data types and what kind of information they can store Explain the difference between a variable and an array Copy and complete the following table, choosing an appropriate variable name and data type for each variable Variable Name Data Type Description deskLength Floating point The length of desk in metres age Integer array A list of peoples ages The number of pupils in a class The name of a ship Your height in metres The number of subjects you take A car registration number
9
Variable Name Data Type Description The average test mark of a class The register of pupil names for a class A list of rainfalls for the month measured in mm A list of fractions A collection of judge scores in a dancing competitions for one competitor
10
Assignments An assignment is when a value is stored in a variable The value stored can either be a literal value, the contents of another variable or the result of a calculation The SET keyword is used to indicate assignments in the reference language pseudocode SET weight TO 70 a literal value SET weight TO newWeight another variable SET weight to oldWeight + change a calculation
11
You can also assign values to the individual elements of an array
You can also assign values to the individual elements of an array. You must identify which element to assign to by including its index SET weight[4] TO oldweight[4] + change Different elements can be changed by using different indices
12
Arithmetic Operators When the variable you are assigning to is of a numeric type like integers and floating points, you can carry out a calculation before assigning the result to the variable The arithmetic operators allow you to carry out these calculation by adding, subtracting, multiplying and dividing values and values stored in variables
13
+ Use + to add two values or variables together, for example: SET total TO bookCost + posterCost - Use - to subtract one value or variable from another, for example: SET moneyLeft TO 20 - bookCost * Use * to multiply two values or variables together, for example: SET total TO posterCost * numberBought
14
/ Use / to divide one value or variable by another, for example SET averageCost TO totalCost / number bought ^ Use ^ to raise one value or variable to the power of another, for example SET cubeVolume TO cubeLength ^ 3
15
Operator Precedence The arithmetic operators have an order of precedence Multiplying and dividing will happen before addition and subtraction. If you want to add or subtract first, you must enclose that part of the calculation inside brackets Not using brackets when necessary is a common cause of logic errors! SET average TO num1 + num2 + num3 / 3 SET average TO (num1 + num2 + num3) / 3
16
String Concatenation When the variable you are assigning to is of a string type, the arithmetic operators can not be used Instead, multiple strings or parts of strings can be joined together. This is called string concatenation SET fullname TO firstname + “ ” + lastname Other operations can be applied to strings, but you do not need to know about them at N5 level
17
Questions – Assignments
Answer questions in full sentences! What is an assignment? List the arithmetic operators – state what each one does Write a line of pseudocode for each of the following assignments: Store the value “Alice” in a variable called name Calculate the totalSales for a concert using the variables costPerTicket and numberOfTicketsSold Using the variable radius, calculate the area of a circle. The area of a circle is the radius squared multiplied by π
18
Identify and correct the errors in the following pseudocode:
A program to calculate the cost of buying juice and crisps for every pupil in a class SET totalCost TO juiceCost + crispCost * noOfPupils A program to calculate the average of 3 numbers SET average TO (num1 + num2 + num3)/2
19
Selection Selection allows a program to process information in different ways When using selection, a condition is evaluated to see if it is either True or False. The program will execute lines of code depending on how the condition is evaluated IF condition THEN … ELSE END IF Any code in here executes if the condition is True Any code in here executes if the condition is False The ELSE part of the IF statement, and the code it executes do not need to be included
20
IF Statement Programming languages implement selection using the IF statement. This example shows a program that applies a 10% discount to the cost of books if more than 100 are bought IF numberBought > 100 THEN totalCost = costPerBook * numberBought * 0.9 ELSE totalCost = costPerBook * numberBought END IF Python doesn’t use and END IF line, instead indentation is used to indicate what code is inside the if statement
21
Conditions You will need to be able to create appropriate conditions for your programs A simple condition compares two values using a comparison operator. The compared values can be either literal values, the contents of a variable or a calculation using the arithmetic operators mark1 + mark2 >= 15 In the above condition, the values stored in the variables mark1 and mark2 are added together and compared to the value 15. If the sum of mark1 and mark2 comes to 15 or more, the condition is evaluated as being True, if the sum of mark1 and mark2 is less than 15, the condition is False
22
Comparison Operators The comparison operators compare two values and return a result of either True or False. There are are six different ways the values can be compared Pseudocode Comparison Python = True if the values on both sides of the operator are exactly the same == ≠ True if the values on both sides of the operator are different != > True if the value on the left side of the operator is more than the value on the right < True if the value on the left side of the operator is less than the value on the right ≥ True if the value on the left side of the operator is the same as or more than the value on the right >= ≤ True if the value on the left side of the operator is the same as or less than the value on the right <=
23
Complex Conditions A simple condition compares two values using a comparison operator. More complex conditions can be created using multiple simple conditions A complex condition usually consists of two or more simple conditions that are joined together using logical operators The logical operators describe how the results of the simple conditions should be evaluated together Like simple conditions, complex conditions will evaluate to a result of either True or False
24
Logical operators There are three logical operators: AND, OR and NOT
Pseudocode How it evaluates Python AND If both of the simple conditions connected by AND are True, the whole condition is True. If only one is True, or if both are False, the whole condition is False and OR If either one of the simple conditions connected by OR is True, the whole condition is True. It is also True if both simple conditions are True The whole condition only evaluates to False if both simple conditions are False or NOT NOT only uses one simple condition, which appears on its right. NOT inverts the value of the condition to its right: True becomes False and False becomes True not
25
Questions – Selection Answer questions in full sentences!
Evaluate the following conditions, stating whether they are True or False. You may assume the variables age, height and name contain the following values: name ≠ “Alice” height > 1.50 age > 14 age ≥ 14 NOT name = “Bob” age = 14 AND height ≤ 1.90 age + 4 < 18 Name = “Alice” OR name = “Bob” 14 1.87 Alice age height name
26
Answer questions in full sentences!
Write down the value in the variable speed after each selection construct has executed SET acceleration TO 5 SET speed TO 10 IF acceleration < 5 THEN SET speed TO speed + acceleration ELSE SET speed TO speed – acceleration END IF SET acceleration TO “Go” SET speed TO “Fast” IF acceleration = “go” THEN SET speed TO “Faster” SET speed TO Slower
27
SET acceleration TO 5 SET speed TO 10 IF acceleration ≤ 5 AND speed > 5 THEN SET speed TO speed + acceleration ELSE SET speed TO speed – acceleration END IF IF acceleration ≥1 AND NOT acceleration < 5 THEN
28
Answer questions in full sentences!
Identify and correct the error in the following sections of pseudocode A program that tells you turn on the heating if the temperature is less than 10oC 1) IF temperature ≤ 10 THEN 2) SEND “Turn heating on” TO DISPLAY 3) END IF A program that displays an error message when the user fails to enter a valid menu number choice between 1 & 3 1) IF choice ≥ 1 AND choice ≤ 3 THEN 2) SEND error message TO DISPLAY Write pseudocode for a program that tell the user that they should be at high school if their age is between 12 and 18
29
Iteration & Fixed Loops
In iteration a line of code, or several lines of code, is executed many times Iteration means programs can be efficient – we only need to write one line of code, but the effect will happen many times. It also reduces the risk of creating an error or bug, which becomes more likely if we have to type the line in several times A fixed loop is a type of programming construct used for iteration. Fixed loops happen a set number of times If a fixed loop is programmed to happen six times, it will always happen exactly six times. If it programmed to happen noOfTimes times, it will happen a number of times equal to the value stored in the variable noOfTimes
30
The FOR loop The FOR loop is an example of a fixed loop. A FOR loop states a start and end value for repetition This example will display the same line ten times: FOR times FROM 1 TO 10 DO SEND “I must not talk in class” TO DISPLAY END FOR Outputs: … Note the lack of an END FOR line in Python Additionally, the range specifies the last number you want to execute the loop with plus 1
31
Loop Control Variables
FOR loops usually have a loop control variable. The loop control variable keeps track of how many times the loop has been completed. The loop control variable can be used to make a FOR loop do something slightly different each time it executes. This example makes it show the six times table: FOR times FROM 1 TO 10 DO SEND “6 times” times “is” times * 6 TO DISPLAY END FOR Outputs: … The first time the loop executes, the value in times is 1, resulting in this line The second time the loop executes, the value in times is 2, resulting in this line
32
Iterating through an array
Iterating through an array is a very common use of FOR loops When iterating through an array, the loop control variable is used as the array index. This means the loop will execute for each value stored in the array This example shows getting input for all the indices in two arrays: FOR EACH pupil FROM pupilNames DO RECEIVE pupilNames[pupil] FROM KEYBOARD RECEIVE pupilMarks[pupil] FROM KEYBOARD END FOR EACH range(0,noOfPupils) means the loop executes noOfPupils times, starting at 0 and ending at noOfPupils - 1 This string concatenation means that the instructions to the user are slightly different each time, making the program more readable
33
REPEAT … TIMES REPEAT … TIMES is an alternative method of writing a fixed loop in pseudocode instead of using a FOR loop The REPEAT … TIMES loop works in the same way as the FOR loop, but it does not have a loop control variable There is no equivalent to this loop in Python and you are only likely to see it in your exam paper. This example works exactly the same as the first FOR loop example – it displays a line ten times: REPEAT 10 TIMES SEND “I must not talk in class” TO DISPLAY END REPEAT
34
Questions – Fixed Loops
Answer questions in full sentences! Give two advantages of using loops to make something happen many times instead of repeating the same line of code? Write down the value in the variable speed after each fixed loop construct has executed SET speed TO 4 FOR counter FROM 1 TO 5 DO SET speed TO counter END FOR SET speed TO 2 FOR counter FROM 1 TO 3 DO SET speed TO speed * speed
35
Answer questions in full sentences!
Identify and correct the error in the following sections of pseudocode A program that prints out the first ten numbers squared 1) FOR i FROM 1 TO 10 DO 2) SEND i “squared is” i * 2 TO DISPLAY 3) END FOR A program that iterates through an array, getting input from the user 1) FOR EACH value IN numbers DO 2) SEND “Enter number” value+1 “below:” TO DISPLAY 3) SET numbers[value +1] FROM KEYBOARD 4) END FOR EACH Write pseudocode for a program that will iterate through the array marks. Each mark will be divided by 20 then multiplied by The result will be stored in the array percentages
36
Conditional Loops A conditional loop does not always happen a fixed number of times. Each time the loop is executed, a boolean condition similar to those used in the IF statement is evaluated. The program uses the evaluated result to decide whether or not to execute the loop again The condition can be evaluated at the start or the end of the loop. If the condition is evaluated at the start of the loop, the loop may not need to be executed at all Some types of loops will execute while the condition is True. Other types of loops will execute as long as the condition is False – they keep on going until the condition is True
37
WHILE loop A WHILE loop is a conditional loop that evaluates its condition at the start of the loop. The body of the loop will execute as long as the condition is True This example WHILE loop keeps executing until the user guesses the correct number WHILE guess ≠ number DO RECEIVE guess FROM KEYBOARD END WHILE SEND well done message TO DISPLAY Outputs: … To make sure this loop happens at least once, we must set the default value of guess to something that is different from the value of number
38
REPEAT UNTIL loop A REPEAT UNTIL loop is a conditional loop that evaluates its condition at the end of the loop. The body of the loop will execute as long as the condition is False This example loop replicates the function of the previous WHILE loop. However, it will always execute at least once so we do not need be careful with the default values of guess and number: REPEAT RECEIVE guess FROM KEYBOARD UNTIL guess = number SEND well done message TO DISPLAY The REPEAT UNTIL loop does not exist in Python – instead you have to use the while loop. Make sure the values in your variables force the loop to execute at least once in this case!
39
Infinite Loops An infinite loop is an example of an execution error. The program becomes stuck in a conditional loop construct and is unable to leave it. This causes the program to appear to stop working, or ‘hang’ Infinite loops occur when you make a mistake that means the result of evaluating the loop condition is always the same, making it impossible to break the loop This example shows a loop that will continue forever: SET speed TO 10 WHILE speed > 5 DO SET acceleration TO speed / 10 END WHILE When creating a conditional loop in your programs, the code inside the loop should always change the variables used in the condition in some way
40
Questions – Conditional Loops
Answer questions in full sentences! Describe two differences between WHILE loops and REPEAT … UNTIL loops Write down the value in the variable speed after each fixed loop construct has executed SET speed TO 10 WHILE speed > 4 DO SET speed TO speed - 1 END WHILE SET speed TO 5 REPEAT SET speed TO speed + speed UNTIL speed ≥ 5
41
Answer questions in full sentences!
Identify and correct the error in the following sections of pseudocode A program that keeps asking the user to enter a number until they enter 0 1) RECEIVE number FROM KEYBOARD 2) WHILE number = 0 3) RECEIVE number FROM KEYBOARD 4) END WHILE A program that slows speed by 1/10th until speed is no longer more than 5 1) SET speed TO 10 2) REPEAT 3) SET acceleration TO speed / 10 4) UNTIL NOT speed > 5 Write pseudocode for a program that will ask the user to enter an amount. The program will calculate 10% of that amount. The program keeps asking for the user to enter an amount until they enter 0, when it stops
42
Input Validation Standard algorithms are simple generic algorithms that can be adapted and reused in your program. At National 5 you only need to know one standard algorithm – Input validation Input validation is a standard algorithm that limits what the user can enter as input to a program. If the input is valid, it is accepted and used in program. Invalid input is rejected and the user is prompted to re-enter it until they enter a valid value You will likely be required to write input validation algorithms in your exam, as well as suggest appropriate values for testing it
43
Input Validation – Numerical Range
Numerical range input validation limits the numbers that can be entered to a program. One or more comparisons are used to specify which numbers are valid and invalid This example shows the variable noOfPeople being validated as a non-zero positive number: RECEIVE noOfPeople FROM KEYBOARD WHILE NOT noOfPeople > 0 DO SEND “Number of people must be positive” TO DISPLAY END WHILE Outputs:
44
Numerical range validation usually has both an upper and lower boundary condition. This example shows the user being forced to enter a number between 1 and 10 as part of a guess the number program RECEIVE guess FROM KEYBOARD WHILE NOT (guess ≥ 1 AND guess ≤ 10) DO SEND “You must enter a number between 1 and 10” TO DISPLAY END WHILE Outputs:
45
Alternative Pseudocodes
RECEIVE guess FROM KEYBOARD WHILE NOT (guess ≥ 1 AND guess ≤ 10) DO SEND error message TO DISPLAY END WHILE WHILE guess < 1 OR guess > 10 DO SEN error message TO DISPLAy REPEAT IF guess < 1 OR guess > 10 THEN END IF REPEAT UNTIL guess ≥ 1 AND guess ≤ 10 These three examples all function exactly the same! Note the use of inverse conditions. Using NOT is a simple way to invert a condition if you need to
46
Input Validation - Text
Restricted choice text input validation works by listing all the words that are valid input. If the word entered by the user isn’t on the list, the input is invalid. Remember that comparing strings is case sensitive! This example forces the user to answer a question with either “Yes” or “No”: RECEIVE getDiscount FROM KEYBOARD WHILE NOT (getDiscount = “Yes” OR getDiscount = “No”) SEND “You must enter Yes or No” TO DISPLAY END WHILE Outputs:
47
Testing Input Validation
Input validation should be tested separately from the reliability of the program. You should have a different test table with normal extreme and exceptional data of its own. For numeric range validation: You need one item of normal test data in the middle of each range of acceptable values You need one item of extreme and one item of exceptional test data for each comparison in the condition WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO 1 x Extreme test data: The number in the comparison, here 1 1 x Exceptional test data: A number outside of the range, below 1 such as -3 1 x Extreme test data: The number in the comparison, here 10 1 x Exceptional test data: A number outside of the range, below 1 such as 12 1 x Normal test data: Any number from middle of range such as 4 or 7
48
WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO
Your expected column of the test data should state if the test data will be accepted or rejected by the input validation. Normal and extreme test data should be accepted by input validation, exceptional test data should be rejected WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO For testing restricted choice text input Test that every entry that should be accepted is Test one item of text that should be rejected guess Expected Actual -3 Reject 1 Accept 4 10 12
49
Questions – Input Validation
Answer questions in full sentences! Create sets of test data to fully test the following examples of input validation An input validation that ensures the user enters a number between 1 & 5 inclusive An input validation that will only accept the user entering the following football positions – goalkeeper, defender, midfielder and striker An input validation that ensure the user enters a valid number of marks for a test out of 20
50
Answer questions in full sentences!
Identify and correct the error in the following sections of pseudocode Input validation to enter a number between 1 and 10 inclusive 1) REPEAT 2) RECEIVE number FROM KEYBOARD 3) IF number < 1 OR number > 10 THEN 4) SEND error message TO DISPLAY 5) END IF 6) UNTIL number > 1 AND number < 10 1) RECEIVE number FROM KEYBOARD 2) WHILE number ≤ 1 AND number ≥ 10 DO 3) SEND error message TO DISPLAY 4) RECEIVE number FROM KEYBOARD 4) END WHILE
51
Answer questions in full sentences!
Write pseudocode for the following input validations Input validation that will only accept the word “Yes”, “No” and “Maybe” Input validation that will accept numbers between 5 and 15 inclusive
52
Predefined Functions A predefined function is a small section of program code that has already been created for you Predefined functions are useful as they can save you time, and often do things that you would be unable to code yourself Predefined functions require parameters. This lets you use the same predefined function is several ways. For example, the predefined function to generate random numbers can make numbers from different ranges depending on the parameters you give it Using the parameters 1 and 10 means our random number will be either 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10
53
Useful Predefined Functions
Random(): Random is a predefined function that generates random numbers within a certain range Integer() Integer is a function that casts data into the integer data type. Strings and floating point data can be turned into and stored as integers. There are also predefined function to turn data into strings, floating points and booleans
54
Round() The round function rounds a floating point value off to a given number of decimal places Length() The length function tells you how many characters are in a string There are many other different predefined functions in addition to these four!
55
Questions – Predefined Functions
Answer questions in full sentences! What is a predefined functions and why are they useful? Explain what is meant by a parameter List and describe four predefined functions and what they down Write down the value in the variable speed after each section of pseudocode SET distance to 5 SET time TO 3 SET speed TO integer(distance/time) SET message TO “Hi There!” SET speed TO length(message)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.