Cambridge Lower Secondary CheckpointStage 7

Programming

Computing Stage 7 Chapter Notes

What this chapter covers

Programming
ShareWhatsAppPost
Programming notes

Unable to load PDF

The notes viewer could not load. Please refresh the page.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Programming notes as text: skim, search, and jump between subtopics.

~15 min read

1. High-Level vs. Low-Level Languages

A program is a set of instructions that tells a computer what to do. At their core, computers only understand 'machine code', which is made of binary ones and zeros. This is a low-level language because it is very close to the computer's hardware and difficult for humans to read or write. To make programming easier, we use high-level languages like Python, Java, or Scratch. These use English-like words and syntax, making them easier to learn and understand. High-level languages must be translated into low-level machine code before the computer can execute them. This translation is done by special programs called compilers or interpreters. Block-based languages (like Scratch) are a visual type of high-level language, while text-based languages (like Python) require you to type the code.

Key term

Translator: A program (either a compiler or an interpreter) that converts source code written in a high-level language into machine code that the processor can execute.

Examiner insight

Examiners reward answers that clearly link 'low-level' to being close to the hardware and 'high-level' to being closer to human language and further from the hardware (more abstract).

Common pitfall

Confusing an interpreter with a compiler. An interpreter translates and runs code one line at a time, whereas a compiler translates the entire program into a separate executable file before it is run.

Worked example 14 marks

Compare two features of a high-level programming language like Python with a low-level language like machine code.

  1. 1

    Feature 1: Readability. High-level languages use English-like keywords (e.g., 'print', 'if') and syntax, making them easy for humans to read, write, and maintain. Low-level languages consist of binary or hexadecimal codes, which are very difficult for humans to understand.

  2. 2

    Feature 2: Portability. High-level language programs can be run on different types of computers with little or no modification. Low-level language programs are specific to one type of processor architecture and are not portable.

Recap

  • Computers only understand low-level machine code (binary).
  • High-level languages use English-like commands and are easier for humans to use.
  • Examples of high-level languages include Python (text-based) and Scratch (block-based).
  • High-level code must be translated into machine code using a compiler or interpreter.
  • Low-level languages are hardware-specific, while high-level languages are generally portable.

Quick check

  1. State one advantage of writing a program in a high-level language compared to a low-level language.1 mark
  2. What is the name of the program that translates high-level code into machine code?1 mark

2. Designing Solutions with Algorithms

Before writing any code, a programmer must have a clear plan. An algorithm is this plan: a finite, step-by-step sequence of instructions designed to solve a specific problem or perform a task. Algorithms must be precise, unambiguous, and guaranteed to terminate. One common way to design and represent an algorithm is by using a flowchart. A flowchart is a diagram that uses standard symbols to visually represent the flow of logic in the algorithm. This makes the program's structure easy to understand for both programmers and non-programmers.

Key term

Algorithm: A finite sequence of well-defined instructions to solve a problem or perform a computation.

Examiner insight

Marks are consistently awarded for using the correct, standard flowchart symbols and connecting them with clear, directional arrows.

Common pitfall

Using the wrong symbol for an operation in a flowchart, for example using a rectangle (process) for an input, which requires a parallelogram.

Worked example 15 marks

Draw a flowchart for an algorithm that calculates the area of a rectangle. The algorithm should take the length and width as inputs and output the calculated area.

  1. 1
    1. Start with an oval 'Start' symbol.
  2. 2
    1. Use a parallelogram for input: 'Input Length, Width'.
  3. 3
    1. Use a rectangle for the process: 'Area = Length * Width'.
  4. 4
    1. Use another parallelogram for output: 'Output Area'.
  5. 5
    1. End with an oval 'Stop' symbol.
  6. 6
    1. Connect all symbols in order with arrows showing the flow of control.

Recap

  • An algorithm is a step-by-step plan for solving a problem.
  • A good algorithm is precise, unambiguous, and has a clear stopping point.
  • A flowchart is a visual diagram representing an algorithm.
  • Standard symbols are used in flowcharts: ovals for start/stop, parallelograms for input/output, and rectangles for processes.
  • Flowcharts help in planning and documenting a program's logic.

Quick check

  1. In a flowchart, what shape is used to represent a process or calculation?1 mark
  2. What is the purpose of an algorithm?1 mark

3. Storing Data: Variables and Data Types

Programs need to store and manipulate data. A variable is a named location in the computer's memory used to store a value. The value of a variable can change as the program runs. Every variable has a data type, which tells the computer what kind of data it is holding. Choosing the correct data type is essential. The main data types are:

  • Integer: Whole numbers, positive or negative (e.g., 10, -5, 0).
  • Real (or Float): Numbers with a decimal point (e.g., 9.81, -0.5, 3.14).
  • String: A sequence of characters, including letters, numbers, and symbols. Strings are always enclosed in quotation marks (e.g., "Hello World", "123 Main St.").
  • Boolean: Can only hold one of two values: True or False. Booleans are fundamental for decision-making in programs.

Key term

Variable: A named storage location in a computer's memory that holds a value which may change during program execution.

Examiner insight

Students who explicitly state the data type of variables when describing an algorithm demonstrate a more complete understanding of program design.

Common pitfall

Attempting to perform mathematical calculations on numbers that are stored as strings. For example, in Python, "2" + "3" results in the string "23", not the integer 5.

Worked example 13 marks

A program is needed to store details about a student: their first name, age, and average grade. For each piece of data, state a suitable variable name and its most appropriate data type.

  1. 1
    1. First Name: Variable name could be 'firstName'. The data type would be String, as it is text.
  2. 2
    1. Age: Variable name could be 'age'. The data type would be Integer, as age is a whole number.
  3. 3
    1. Average Grade: Variable name could be 'averageGrade'. The data type would be Real (or Float), as the average may have a decimal point (e.g., 85.5).

Recap

  • A variable is a named memory location for storing data.
  • The value stored in a variable can be changed during program execution.
  • An Integer is a whole number.
  • A Real or Float is a number with a decimal part.
  • A String is a sequence of text characters.
  • A Boolean can only be True or False.

Quick check

  1. What is the most appropriate data type for storing the price of an item, such as £4.99?1 mark
  2. What data type would you use to store whether a light is switched on or off?1 mark

4. Program Flow: Sequence and I/O

Sequence is the most basic control structure in programming. It means that the computer will execute instructions one after another, in the order they are written in the program, from top to bottom. For a program to be useful, it needs to interact with the user. This is done through Input and Output (I/O). Input is any data the program receives from a user or another source (e.g., typing on a keyboard). Output is any data the program sends out to the user (e.g., displaying text on the screen). In Python, the `input()` function is used to get data from the user, and the `print()` function is used to display output.

Key term

Sequence: The control structure where instructions are executed one after another in the order they appear in the program.

Examiner insight

Clear input prompts (e.g., 'Enter your age:') and well-formatted output messages are expected and contribute to marks for code clarity and user-friendliness.

Common pitfall

Forgetting to convert the string from an `input()` function into a number (integer or float) before trying to use it in a mathematical calculation. This will cause a runtime error or incorrect string concatenation.

Worked example 13 marks

Write a Python program that asks for the user's name and their favourite subject, and then prints a message combining these two inputs.

  1. 1
    1. Use the input() function to ask for the user's name and store it in a variable: `name = input("What is your name? ")`
  2. 2
    1. Use the input() function again to ask for their favourite subject: `subject = input("What is your favourite subject? ")`
  3. 3
    1. Use the print() function to display the combined message: `print("Hello " + name + ", your favourite subject is " + subject + ".")`

Recap

  • Sequence means instructions are run in order from top to bottom.
  • Input is data received by the program, often from the user.
  • Output is data sent from the program, often displayed on the screen.
  • In Python, `input()` gets user input and `print()` displays output.
  • Data from `input()` is always a string and may need converting to a number.

Quick check

  1. What is the name of the Python function used to display text on the screen?1 mark
  2. By default, what data type is the value returned by Python's `input()` function?1 mark

5. Making Decisions with Selection

Programs often need to make choices and follow different paths based on certain conditions. This is achieved using selection. The most common form of selection is the IF...THEN...ELSE structure. The program checks a condition: IF the condition is true, THEN it executes one block of code. ELSE (if the condition is false), it executes a different block of code. In Python, this is written using `if`, `elif` (else if), and `else` statements. The code blocks that belong to each part of the statement are indented to show they are part of that condition. Conditions often use comparison operators like `==` (equal to), `!=` (not equal to), `>` (greater than), and `<` (less than).

Key term

Selection: A control structure that allows a program to execute different lines of code depending on whether a condition is evaluated as true or false.

Examiner insight

Correct indentation is not just a matter of style in Python; it defines the program's logic. Examiners will penalise code with incorrect indentation as it is a fundamental syntax error.

Common pitfall

Using a single equals sign (`=`), which is the assignment operator, inside an `if` condition instead of the double equals sign (`==`), which is the comparison operator.

Worked example 14 marks

Write a Python program that asks for a user's age. If the age is 18 or over, it should print 'Access granted'. Otherwise, it should print 'Access denied'.

  1. 1
    1. Get the user's age and convert it to an integer: `age = int(input("Please enter your age: "))`
  2. 2
    1. Start the if statement to check the condition: `if age >= 18:`
  3. 3
    1. Indent the code to be executed if the condition is true: ` print("Access granted")`
  4. 4
    1. Add the else part for when the condition is false: `else:`
  5. 5
    1. Indent the code for the else block: ` print("Access denied")`

Worked example 25 marks

A program needs to grade a test score. If the score is above 80, print 'Distinction'. If it is between 60 and 80 (inclusive), print 'Merit'. Otherwise, print 'Pass'. Write the Python code.

  1. 1
    1. Get the score as a number: `score = int(input("Enter test score: "))`
  2. 2
    1. Check the first condition for 'Distinction': `if score > 80:`
  3. 3
    1. Print the result: ` print("Distinction")`
  4. 4
    1. Use `elif` for the second condition: `elif score >= 60:` (This is only checked if the first `if` was false, so we don't need to check if score <= 80)
  5. 5
    1. Print the result: ` print("Merit")`
  6. 6
    1. Use `else` to catch all other cases: `else:`
  7. 7
    1. Print the final result: ` print("Pass")`

Recap

  • Selection allows a program to make decisions.
  • The `if` statement checks if a condition is true.
  • The `else` statement provides an alternative block of code if the condition is false.
  • The `elif` statement allows for checking multiple conditions in sequence.
  • Indentation is crucial in Python to define which code belongs to the `if`, `elif`, or `else` blocks.
  • Comparison operators like `==`, `>`, `<`, `>=`, `<=` are used to form conditions.

Quick check

  1. What is the difference between `=` and `==` in Python?2 marks

6. Repeating Code with Iteration

Iteration, or looping, allows a block of code to be executed repeatedly. This saves time and makes code more efficient. There are two main types of iteration:

  1. Count-Controlled (Definite) Iteration: This is used when you know exactly how many times you want the loop to run. In Python, this is done with a `for` loop, often used with the `range()` function (e.g., `for i in range(5):` will run the loop 5 times).
  2. Condition-Controlled (Indefinite) Iteration: This is used when you want the loop to repeat as long as a certain condition is true. The number of repetitions is not known in advance. In Python, this is done with a `while` loop (e.g., `while password != "secret":` will keep looping until the correct password is entered).

Key term

Iteration: The repetition of a block of code within a computer program, commonly implemented using FOR or WHILE loops.

Examiner insight

Answers that correctly identify whether a FOR loop (definite iteration) or a WHILE loop (indefinite iteration) is more appropriate for a given problem scenario score higher.

Common pitfall

Creating an infinite loop with a `while` statement. This happens if the code inside the loop never changes the variables in the condition, meaning the condition will always remain true.

Worked example 13 marks

Write a Python program using a `for` loop to print the 5 times table, from 1 x 5 to 12 x 5.

  1. 1
    1. Start the for loop to iterate from 1 to 12. The `range` function needs to go up to 13 to include 12: `for i in range(1, 13):`
  2. 2
    1. Inside the loop, calculate the result: `result = i * 5`
  3. 3
    1. Print the formatted result: `print(i, "x 5 =", result)`

Worked example 24 marks

Write a Python program using a `while` loop that asks the user to enter a password. The program should keep asking until the user enters the word 'python'.

  1. 1
    1. Initialise a variable for the password to an empty string: `password = ""`
  2. 2
    1. Set up the while loop with the condition to continue as long as the password is not 'python': `while password != "python":`
  3. 3
    1. Inside the loop, ask the user for the password: ` password = input("Enter the password: ")`
  4. 4
    1. After the loop finishes (meaning the correct password was entered), print a confirmation message: `print("Password accepted.")`

Recap

  • Iteration is used to repeat blocks of code.
  • A `for` loop is used for definite iteration (when the number of repeats is known).
  • A `while` loop is used for indefinite iteration (repeating as long as a condition is true).
  • The `range()` function is often used with `for` loops to specify the number of iterations.
  • Be careful to avoid infinite loops with `while` statements by ensuring the condition can eventually become false.

Quick check

  1. Which type of loop (for or while) would be best for iterating through a list of 10 known items?1 mark

7. Finding and Fixing Errors (Debugging)

Even experienced programmers make mistakes. The process of finding and fixing these mistakes, or 'bugs', is called debugging. There are three main types of errors you will encounter:

  1. Syntax Errors: These are errors in the grammar of the programming language. For example, misspelling a keyword (`prnt` instead of `print`), forgetting a colon, or having incorrect indentation. The translator (interpreter or compiler) will usually detect these and stop the program from running, often with a helpful error message.
  2. Logic Errors: These are flaws in the algorithm or design of the program. The program will run without crashing, but it will produce an incorrect or unexpected result. For example, using `+` instead of `*` to calculate an area. These are often the hardest errors to find and require careful testing.
  3. Runtime Errors: These errors only occur when the program is executing (running). They are not syntax errors, but cause the program to crash. A common example is trying to divide a number by zero, or trying to convert a non-numeric string like "hello" into an integer.

Key term

Debugging: The systematic process of finding and correcting errors (bugs) in a computer program.

Examiner insight

Students who can not only identify an error but also correctly name its type (syntax, logic, or runtime) and explain why it is an error demonstrate a superior understanding.

Common pitfall

Assuming a program is correct just because it runs without an error message. Logic errors are silent and can only be found by testing the program with a range of inputs and comparing the output to the expected results.

Worked example 14 marks

The following Python code is intended to ask for two numbers and print their average. It contains one syntax error and one logic error. Identify and correct both.

  1. 1

    Original Code: `num1 = int(input("Enter first number: "))` `num2 = int(input("Enter second number: "))` `average = num1 + num2 / 2` `print("The average is" average)`

  2. 2
    1. Identify Syntax Error: The `print` statement is missing a comma between the string and the variable. It should be `print("The average is", average)`.
  3. 3
    1. Identify Logic Error: The calculation `num1 + num2 / 2` will perform the division first due to operator precedence. This calculates `num1 + (num2 / 2)`. To get the correct average, the addition must be done first.
  4. 4
    1. Correct Logic Error: Use parentheses to enforce the order of operations: `average = (num1 + num2) / 2`.

Recap

  • Debugging is the process of finding and fixing errors in a program.
  • Syntax errors are grammatical mistakes that prevent the program from running.
  • Logic errors cause the program to produce incorrect results, even though it runs.
  • Runtime errors cause the program to crash during execution.
  • Thorough testing is essential to find and eliminate logic errors.

Quick check

  1. What type of error is it if you try to divide a number by zero?1 mark
  2. What type of error is it if your program runs but calculates the wrong total?1 mark

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. Explain the difference between a high-level language and a low-level language, giving one example of each.3 marks
  2. For each of the following values, identify the most appropriate data type (Integer, Real, String, or Boolean): a) "01223 555 901", b) -45, c) True, d) 12.54 marks
  3. Draw a flowchart for an algorithm that asks a user for a temperature in Celsius. If the temperature is 0 or below, it should output 'Freezing'. Otherwise, it should output 'Not freezing'.5 marks
  4. Write a Python program that asks the user to enter the length and width of a rectangle, calculates the perimeter, and prints the result in a user-friendly sentence.4 marks
  5. The following Python code contains a syntax error and a logic error. Identify and correct both errors. # Code to add two numbers number1 = input("Enter first number: ") number2 = input("Enter second number: ") total = number1 + number2 print(The total is, total)4 marks
  6. Explain the difference between a FOR loop and a WHILE loop, giving a specific example scenario where each would be the most appropriate choice.4 marks
  7. Write a Python program that simulates a simple login system. It should use a WHILE loop to repeatedly ask the user for a username and password. The loop should only stop when the username is 'admin' AND the password is '1234'.6 marks
  8. What is an algorithm? Explain one reason why it is important to design an algorithm before starting to write program code.3 marks
  9. A cinema ticket costs £12 for an adult and £8 for a child. Write a Python program that asks the user how many adult tickets and how many child tickets they want, and then calculates and displays the total cost.5 marks
  10. What is debugging? Name and briefly describe two different types of program error.3 marks

Go deeper

Practise and revise with member-only material for this chapter.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters