Cambridge Lower Secondary CheckpointStage 8

Programming

Computing Stage 8 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. Planning with Algorithms and Pseudocode

Before writing any code, it's crucial to have a clear plan. An algorithm is a step-by-step set of instructions to solve a problem or complete a task. Think of it as a recipe for a computer. Pseudocode is a tool programmers use to write out these algorithms. It's not a real programming language, but a structured, English-like way to describe the steps a program will take. This allows you to focus on the logic of the solution without worrying about the specific syntax of a language like Python. A good pseudocode plan makes the actual coding process much faster and less error-prone.

Key term

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

Examiner insight

Examiners look for clear, logical steps that correctly solve the problem, using standard pseudocode conventions for input, processing, and output.

Common pitfall

Writing pseudocode that is too close to a specific programming language's syntax, which defeats its purpose as a language-independent planning tool.

Worked example 15 marks

A program is required to ask a user for two numbers, add them together, and display the result. Write the pseudocode for this algorithm.

  1. 1

    Step 1: Start the algorithm. Use a keyword like START or BEGIN.

  2. 2

    START

  3. 3

    Step 2: Prompt the user for the first number and store it. Use a keyword like INPUT or READ.

  4. 4

    OUTPUT 'Enter the first number:'

  5. 5

    INPUT number1

  6. 6

    Step 3: Prompt the user for the second number and store it.

  7. 7

    OUTPUT 'Enter the second number:'

  8. 8

    INPUT number2

  9. 9

    Step 4: Perform the calculation and store the result in a new variable.

  10. 10

    SET total = number1 + number2

  11. 11

    Step 5: Display the final result to the user. Use a keyword like OUTPUT or PRINT.

  12. 12

    OUTPUT 'The total is: ' + total

  13. 13

    Step 6: End the algorithm. Use a keyword like END or STOP.

  14. 14

    END

Recap

  • An algorithm is a step-by-step plan to solve a problem.
  • Pseudocode is a way of writing an algorithm using structured English.
  • Pseudocode helps you plan program logic before you start coding.
  • Common pseudocode keywords include INPUT, OUTPUT, SET, IF, ELSE, and END.
  • Planning with pseudocode makes coding easier and reduces logic errors.

Quick check

  1. What is the purpose of using pseudocode in program development?2 marks
  2. Write a single line of pseudocode to get a user's age and store it in a variable called 'userAge'.1 mark

2. Python Fundamentals: Variables and Data Types

Python is a high-level, text-based programming language known for its simple and readable syntax. A fundamental concept in Python, and all programming, is the 'variable'. A variable is a named container in the computer's memory used to store data. Each piece of data has a 'type'. The main data types you need to know are:

  • Integer (int): Whole numbers, like 10, -5, or 0.
  • Float: Numbers with a decimal point, like 3.14 or -25.5.
  • String (str): Text, enclosed in single (' ') or double (" ") quotes, like 'Hello' or "IGCSE Computer Science".
  • Boolean (bool): Represents one of two values: True or False. These are crucial for making decisions in programs.

You create a variable in Python by choosing a name and using the assignment operator (=) to give it a value, for example: `score = 100`.

Key term

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

Common pitfall

Confusing the assignment operator (=) with the equality comparison operator (==). The single equals sign assigns a value, while the double equals sign checks if two values are equal.

Fun fact

Python is named after the British comedy group Monty Python, not the snake! The creator, Guido van Rossum, was a fan of the show.

Worked example 14 marks

Write a Python program that asks for a user's name and age. It should then print a message that says 'Hello [Name], you are [Age] years old.'.

  1. 1

    Step 1: Use the input() function to ask for the user's name and store it in a variable called 'name'. The input will be a string.

  2. 2

    name = input('What is your name? ')

  3. 3

    Step 2: Use the input() function to ask for the user's age. The input will be a string, so we need to convert it to an integer using int().

  4. 4

    age_str = input('What is your age? ')

  5. 5

    age = int(age_str)

  6. 6

    Step 3: Use the print() function to display the final message. You can use an f-string (formatted string) to easily embed the variables.

  7. 7

    print(f'Hello {name}, you are {age} years old.')

Recap

  • A variable is a named location for storing data.
  • The main Python data types are Integer (int), Float, String (str), and Boolean (bool).
  • Use the equals sign (=) as the assignment operator to give a variable a value.
  • The `input()` function always returns a string, so you may need to convert it using `int()` or `float()`.

Quick check

  1. What are the data types of the following values: 42, "42", 42.0, False?2 marks
  2. Write one line of Python code to create a variable called 'price' and assign it the floating-point value 9.99.1 mark

3. Making Decisions: Selection with IF, ELIF, ELSE

Programs often need to make choices and run different code depending on certain conditions. This is called 'selection'. In Python, selection is primarily handled using `if`, `elif` (short for 'else if'), and `else` statements. The structure works like this: the program checks an `if` condition. If it's true, the indented block of code below it runs, and the rest of the structure is skipped. If it's false, the program checks the next `elif` condition. This continues until a true condition is found or it reaches the `else` block, which runs if all preceding conditions were false. Conditions are formed using comparison operators (e.g., `==` for equal to, `>` for greater than, `!=` for not equal to) and can be combined using logical operators (`and`, `or`, `not`).

Key term

Selection: A control structure in programming that allows the program to execute different blocks of code based on whether a condition is true or false.

Examiner insight

Examiners award marks for the correct use of `if/elif/else` structure and accurate logical conditions. Ensure your code correctly handles all possible paths, including the boundaries (e.g., exactly 140cm in the example).

Fun fact

The concept of selection in programming dates back to the 19th century with Ada Lovelace's work on the Analytical Engine, where she described how the machine could make choices based on conditions.

Worked example 15 marks

A theme park ride has the following rules: you must be at least 140cm tall. If you are over 190cm, you are too tall. Write a Python program that asks for a user's height and prints 'You can ride.', 'You are too short.', or 'You are too tall.' as appropriate.

  1. 1

    Step 1: Get the user's height as an integer.

  2. 2

    height = int(input('Enter your height in cm: '))

  3. 3

    Step 2: Use an 'if' statement to check the first condition: if the height is less than the minimum.

  4. 4

    if height < 140:

  5. 5

    print('You are too short.')

  6. 6

    Step 3: Use an 'elif' statement to check the next condition: if the height is greater than the maximum.

  7. 7

    elif height > 190:

  8. 8

    print('You are too tall.')

  9. 9

    Step 4: Use an 'else' statement to handle all other cases, which means the height is valid.

  10. 10

    else:

  11. 11

    print('You can ride.')

Recap

  • Selection allows a program to make decisions.
  • Python uses `if`, `elif`, and `else` for selection.
  • Indentation is mandatory in Python to define which code block belongs to a statement.
  • Comparison operators like `==`, `!=`, `>`, `<`, `>=`, `<=` are used to form conditions.
  • Logical operators `and`, `or`, `not` can be used to create complex conditions.

Quick check

  1. What is the keyword in Python for 'else if'?1 mark
  2. Write a condition to check if a variable 'score' is between 50 and 100, inclusive.2 marks

4. Repetition with Loops: Iteration

Iteration means repeating a section of code. This is essential for automating repetitive tasks. Python has two main types of loops: `for` loops and `while` loops.

FOR Loops (Count-Controlled): A `for` loop is used when you know how many times you want to repeat the code. It iterates over a sequence (like a list of items or a range of numbers). The `range()` function is very useful here. For example, `for i in range(5):` will execute the loop body 5 times (with `i` being 0, 1, 2, 3, and 4).

WHILE Loops (Condition-Controlled): A `while` loop is used when you want to repeat code as long as a certain condition is true. The number of repetitions might not be known in advance. The loop continues to run until its condition becomes false. It's vital to ensure that something inside the loop eventually makes the condition false, otherwise you'll create an infinite loop.

Key term

Iteration: The process of repeating a block of code multiple times, typically using a 'for' or 'while' loop.

Common pitfall

Creating an infinite `while` loop by forgetting to include code inside the loop that changes the loop's condition (e.g., forgetting to increment a counter or ask for new input).

Worked example 14 marks

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

  1. 1

    Step 1: Use a `for` loop with the `range()` function. To go from 1 to 12, we need `range(1, 13)` because the end value is exclusive.

  2. 2

    for i in range(1, 13):

  3. 3

    Step 2: Inside the loop, calculate the result of the current number `i` multiplied by 7.

  4. 4

    result = i * 7

  5. 5

    Step 3: Print the result in a formatted string.

  6. 6

    print(f'{i} x 7 = {result}')

Worked example 24 marks

Write a Python program that repeatedly asks the user to 'Enter password:' until they type the correct password, which is 'secret123'. When they are correct, it should print 'Access granted.'

  1. 1

    Step 1: Initialize a variable to store the user's guess. We can set it to an empty string initially.

  2. 2

    guess = ''

  3. 3

    Step 2: Create a `while` loop that continues as long as the guess is not equal to the correct password.

  4. 4

    while guess != 'secret123':

  5. 5

    Step 3: Inside the loop, ask the user for their input.

  6. 6

    guess = input('Enter password: ')

  7. 7

    Step 4: After the loop finishes (which only happens when the password is correct), print the success message.

  8. 8

    print('Access granted.')

Recap

  • Iteration is the repetition of a block of code.
  • Use a `for` loop for a fixed number of repetitions (count-controlled).
  • Use a `while` loop for repetitions that depend on a condition being true (condition-controlled).
  • The `range(start, stop)` function is often used with `for` loops.
  • Always ensure a `while` loop's condition can eventually become false to avoid an infinite loop.

Quick check

  1. Which type of loop would be best for printing the name of every student in a class list?1 mark
  2. What is an infinite loop?1 mark

5. Expanding Functionality with Libraries

You don't have to write every single piece of code from scratch. A 'library' (or 'module' in Python) is a collection of pre-written, reusable code that you can add to your program. This saves a huge amount of time and allows you to perform complex tasks easily. To use a library, you first have to `import` it into your program. Once imported, you can use its functions by typing the library's name, a dot, and then the function's name. Two very common and useful libraries are:

  • random: Provides functions for generating random numbers. For example, `random.randint(a, b)` gives a random integer between `a` and `b` (inclusive).
  • time: Provides time-related functions. A useful one is `time.sleep(s)`, which pauses your program's execution for `s` seconds.

Key term

Library: A collection of pre-written code, functions, and routines that a programmer can import and use to perform common tasks.

Fun fact

The Python Package Index (PyPI) is a vast repository of third-party libraries for Python, containing over 400,000 projects that can do almost anything, from data science and machine learning to game development.

Worked example 13 marks

Write a Python program that simulates rolling a standard six-sided die and prints the result.

  1. 1

    Step 1: Import the `random` library to get access to its functions.

  2. 2

    import random

  3. 3

    Step 2: Use the `random.randint()` function to generate a random integer between 1 and 6.

  4. 4

    roll = random.randint(1, 6)

  5. 5

    Step 3: Print the result to the user.

  6. 6

    print(f'You rolled a {roll}')

Worked example 24 marks

Write a Python program that prints a countdown from 3 to 1, with a one-second pause between each number, and then prints 'Liftoff!'.

  1. 1

    Step 1: Import the `time` library to use the sleep function.

  2. 2

    import time

  3. 3

    Step 2: Print each number in the countdown.

  4. 4

    print('3')

  5. 5

    Step 3: Use `time.sleep(1)` to pause for one second.

  6. 6

    time.sleep(1)

  7. 7

    Step 4: Repeat for the numbers 2 and 1.

  8. 8

    print('2')

  9. 9

    time.sleep(1)

  10. 10

    print('1')

  11. 11

    time.sleep(1)

  12. 12

    Step 5: Print the final message.

  13. 13

    print('Liftoff!')

Recap

  • Libraries are collections of pre-written code that extend a program's capabilities.
  • Use the `import` keyword to bring a library into your program.
  • Call library functions using the format `library_name.function_name()`.
  • The `random` library is used for generating random numbers.
  • The `time` library is used for time-related tasks, like pausing the program.

Quick check

  1. Write the line of code needed to use functions from the `random` library.1 mark
  2. Which function from the `random` library would you use to pick a random winner from a list of names?1 mark

6. Ensuring Quality: Testing and Debugging

Writing a program is only half the battle; you must also ensure it works correctly. This involves testing (checking the program for errors) and debugging (finding and fixing those errors). There are three main types of errors:

  1. Syntax Errors: Mistakes in the language's grammar, like typos (`prnt` instead of `print`) or missing punctuation (`:` or `"`). These errors prevent the program from running at all.
  2. Runtime Errors: Errors that occur while the program is running, often causing it to crash. An example is trying to divide by zero or converting a non-numeric string like 'hello' to an integer.
  3. Logic Errors: The program runs without crashing but produces the wrong output. This is often the hardest type of error to find, as the computer is doing exactly what you told it to do, but what you told it to do was wrong.

To test effectively, programmers create a test plan. This is a formal document that outlines what will be tested. It includes the test data to be used, the expected outcome, and a space to record the actual outcome. Good test plans use a variety of data: normal (typical, valid data), boundary (data at the limits of what's acceptable), and erroneous (invalid data that should be rejected).

Key term

Debugging: The systematic process of finding and fixing errors, or 'bugs', in a computer program.

Examiner insight

Marks are frequently awarded for creating a comprehensive test plan. To get full marks, you must show you have considered all three types of test data: normal, boundary, and erroneous.

Fun fact

The term 'bug' for a computer error was popularized after a moth was found trapped in a relay of the Harvard Mark II computer in 1947, causing it to malfunction. The technicians 'debugged' the computer by removing the moth.

Worked example 16 marks

A program asks for a user's age to see if they get a discount. The discount applies to ages 18 and under, and 65 and over. Create a test plan with at least 4 test cases for this program.

  1. 1

    Step 1: Create a table with columns: Test Number, Test Data (Age), Test Type, Expected Outcome, Actual Outcome.

  2. 2

    | Test No. | Test Data (Age) | Test Type | Expected Outcome | Actual Outcome |

  3. 3
  4. 4

    Step 2: Add a 'normal' data test case that should get a discount (e.g., age 16).

  5. 5

    | 1 | 16 | Normal | 'Discount applied' | |

  6. 6

    Step 3: Add a 'normal' data test case that should not get a discount (e.g., age 30).

  7. 7

    | 2 | 30 | Normal | 'Full price' | |

  8. 8

    Step 4: Add 'boundary' data test cases. These are the critical edge cases: 18 and 65.

  9. 9

    | 3 | 18 | Boundary | 'Discount applied' | |

  10. 10

    | 4 | 65 | Boundary | 'Discount applied' | |

  11. 11

    Step 5: Add another boundary case just outside the valid range (e.g., 19 and 64).

  12. 12

    | 5 | 19 | Boundary | 'Full price' | |

  13. 13

    | 6 | 64 | Boundary | 'Full price' | |

  14. 14

    Step 6: Add an 'erroneous' data test case that the program should handle gracefully (e.g., a negative number or text).

  15. 15

    | 7 | -5 | Erroneous | 'Invalid age entered' | |

Recap

  • Syntax errors are grammatical mistakes that stop the program from running.
  • Runtime errors happen during execution and can crash the program.
  • Logic errors cause incorrect results even though the program runs.
  • A test plan is a document used to systematically test a program.
  • Effective testing uses normal, boundary, and erroneous data.

Quick check

  1. A program to calculate area multiplies length by length instead of length by width. What type of error is this?1 mark
  2. What is the difference between boundary and erroneous test data?2 marks

End-of-chapter exercise

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

  1. Identify the most appropriate data type (Integer, String, Float, or Boolean) for storing each of the following pieces of information: a) A person's name, b) The number of students in a class, c) Whether a light is on or off, d) The price of a chocolate bar.4 marks
  2. Write a pseudocode algorithm that asks a user for the length and width of a rectangle, calculates the area (length * width), and displays the result.4 marks
  3. The following Python code contains three syntax errors. Identify and correct them. score = input("Enter your score: ") if score >= 50 print(You passed!) else: print("You failed.")3 marks
  4. Write a Python program that asks the user to enter a number. The program should print 'Positive' if the number is greater than 0, 'Negative' if it is less than 0, and 'Zero' if it is exactly 0.5 marks
  5. Write a Python program that uses a `for` loop to print all the odd numbers from 1 to 20.4 marks
  6. Explain the difference between a count-controlled loop (like `for`) and a condition-controlled loop (like `while`). Provide a simple example scenario where each would be the better choice.4 marks
  7. A website requires a new password to be between 8 and 12 characters long (inclusive). Create a test plan with 5 test cases to check the validation code for the password length. Include normal, boundary, and erroneous data.5 marks
  8. Using the `random` library, write a Python program for a simple guessing game. The program should choose a random number between 1 and 20. It should then ask the user to guess the number. The program should use a `while` loop to keep asking until the user guesses correctly, at which point it should print 'You got it!'.6 marks
  9. What is the purpose of a program library? Name one Python library and describe a function it contains and what that function does.3 marks
  10. Translate the following pseudocode into a working Python program. START SET total = 0 SET count = 0 WHILE count < 5 OUTPUT 'Enter a number:' INPUT number total = total + number count = count + 1 ENDWHILE OUTPUT 'The total is: ' + total END6 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