Topic 2_ Programming (i-GCSE)Computer Science
Topic 2_ Programming (i-GCSE)Computer Science
Computer Science
29th November 2023
Lesson 1
● Developing Algorithms and Pseudocode
Learning Objectives
1_ Data types
Boolean - 2 outcomes. for example: yes or no
* (Multiply)
(==) Equal to
+ (Concatenate)
Sequence
1
14th December 2023
(2 hour lesson 2 and 3)
Programming constructs
2
Task 1
1. Draw a flow diagram for an algorithm which calculates how much money a student will
need per week to buy a meal and two drinks each weekday. The user should be
prompted to enter how much a meal costs, how much a drink costs, and then calculate
and display the total required.
3
Task 2 - Draw a flow diagram for an algorithm which asks someone
to enter their age in years. It then calculates the number of days they
have been alive. Assume that there are 365 days in each year. You
only need to calculate the whole years that they have been alive.
15*365 = 5475
No of days / 365
5475/365 = no of years
4
Task 3
Jasmine plays a game on her computer screen. A moving balloon appears on the screen, and
she has to pop the balloon by clicking on it with the mouse. When the balloon is popped another
one appears. The aim of the game is to pop as many balloons as possible in one minute.
5
(e) Add a flowchart box at the bottom to display the player’s score. Display player score in
output box
Task 2 answer
Task 3 - Create a flowchart for an algorithm that finds the maximum of three numbers.
6
INput — Process — Output
Output num 2
Output num 2
Task 4 - Michael is writing a program for a dice game played with three dice.
(a) The player rolls the dice, and is given points according to the following algorithm.
7
State the value of the scores if the dice rolled are:
246 - answer is 0
551 - answer is 9
444 - answer is 12
(b) Some rolls of the dice produce a negative score. State a set of three numbers that can
be used to test whether the algorithm produces a negative score when it should, and state the
expected output of your test data.
8
Homework
Task 5
An amusement park operates a smartcard system for visitors. When they enter the park, a
visitor chooses the amount they wish to put on their card. Rides cost differing amounts, and to
get through a barrier for a particular ride, the visitor inserts their card. The balance on the card is
checked. If there is enough money on the card, the balance is updated and displayed and the
barrier opens. If there is not enough money left on the card, the current balance is displayed
with a message “Not enough for this ride – need to top up”.
9
28th December 2023 - 1-3pm
Continue Flowcharts and algorithms
Practice Questions
1) An algorithm is to be written which calculates the average of a set of student marks
entered. If -1 is entered, then the program ends. The flowchart on the next page
describes the steps in the algorithm. However, most of the stages have been omitted.
(a) Complete the flowchart, using the item number from the list of
items given below.
1 Is mark = -1?
2 INPUT "Enter next mark"
3 OUTPUT "No marks entered"
4 INPUT mark
5 count ←- count + 1
6 OUTPUT average
7 total ←-0
8 Is count ←0?
9 total ←total + mark
10 average ←- total / count
10
11
The below table shows a number of Boolean expressions. For each one, state whether
it evaluates to TRUE or FALSE. The first row has been completed for you .
Evaluates Evaluates
Expression Expression
to… to…
12
Indentation (spacing)
Colon :
Semi colon ;
If then else s
tatements
Loops - for next, while end while
Programming constructs
03/01/24
Objectives
13
Complete the flowchart to show the following
pseudocode
mealCost = 4.00
drinkCost = 2.00
total = mealCost + drinkcost
Programming constructs
How to apply data types in programming ( how the color of the text changes when the data type
is different for example string would be green)
i.
1.Data types used: boolean, float, string, integer (int).
2. How to apply programming constructs
3. I learned syntax errors
4. Syntax used in Python such as collon “:”, indentation (tab)
5. Boolean operators and boolean expressions ( i should revise the names of these things
so its easier for me to remember what they are
14
Homework - To be completed before next lesson
Make a list of all keywords we have covered so far and write its meaning with examples.
# PROCESS //Comment
discount_amount =
(discount_percentage / 100) *
marked_price
sale_price = marked_price -
discount_amount
#OUTPUT//Comment
print(f"Marked Price:
£{marked_price}")
print(f"Discount Percentage:
{discount_percentage}%")
print(f"Sale Price:
£{sale_price}")
15
This is the output
Enter the marked price: 2.30
Enter the discount
percentage: 20
Marked Price: $2.3
Discount Percentage: 20.0%
Sale Price:
$1.8399999999999999
2) How you do write a pseudocode and code for input and output
16
Assign the answer to a variable called age
*
23rd January 2024
Learning objective
Keywords
Abstraction- representing ‘real world problems in a computer using variables and symbols and
removing unnecessary elements from the problems
Decomposition- breaking a problem into smaller parts. It can be easier to solve smaller parts.
17
Battle ships
Position ships on
18
Check
Check if all
contents of
ships
grid
found
position
Choose
grid Display hit Display won
position
Check
Generate contents of
Save ship
random grid
position
position
position
Practice examples
19
Write an algorithm, pseudocode and code (python) that takes a user’s mark as input and
outputs:
● "Pass" if they scored on, or over 50
● "Merit if they scored on, or over 70
● "Distinction" if they scored on, or over 90 or "Fail" if below 50
Input
Pseudocode
Input mark
If
Mark is greater than 50 and lesser than 69 THEN “pass”
Else
Mark is greater than 70 and lesser than 89 THEN “Merit”
Else
Mark is greater than 90 THEN “Distinction
Else
Mark lesser than 50 THEN fail
== (equal to)
2/ 6/ 2024
Lesson objectives
•use arithmetic operators
use variables in algorithms and programs
use arithmetic operators and BIDMAS
layout code to be readable and maintainable
20
Predictions,
1. 15
2. 9
3 .4.4
4. 4
5. 25
6. 88
2/11/2024
Input –) (number_one
Input –) (number_two
20th of february
-meaning of program
-IDE integrated development environment to work with a python program
-use arithmetic operators (<,>,=,!=, ==, *,+,-,/)
IDE- every program has its own IDE. IDEs are tools that make code writing, debugging and
testing your code easier. It provides helpful features like code completion, debugging tools etc…
#input
21
side_length = int(input("enter number"))
#process
surface_area_of_the_cube = side_length*side_length*6
#output
print(surface_area_of_the_cube)
IDE produces error messages that be used to help you with fixing
problems.
1. height = 4
2. print(height * width)
3. width = 7
height = 4
width = 7
print(height * width)
22
Lesson Objectives
Learn about different types of errors
Understand what causes these errors
Learn how to resolve these errors
What are build in data types in Python?
How can you convert one datatype to another in Python?
# using LISTS
adjectives = ["silly", "goofy", "absurd", "ridiculous", "ludicrous"]
nouns = ["noodle", "muffin", "banana", "pickle", "sock"]
23
Homework - 27th February 2024
Q1) Show with an example how you take input and create output.
Using input() and print() to make a responsive program.
Q3) Find and fix runtime errors. Show with a help of an example
Lesson objectives
Learn about modules and how they are used in a program
Learn the structure of the code written in 3 parts, import libraries, Subprograms and Main
programs
Project - Personal PIN generator (add comments # in this program to explain what is
going on- HW)
#
import random
#
def generate_pin(birthday):
random.seed(birthday)
pin = random.randint(1000, 9999)
return pin
#
birthday = int(input("Enter your birthday (in the form DDMMYYYY): "))
pin = generate_pin(birthday)
24
3/7/24
Activity 1
Use this string from the opening of The Canterbury Tales to complete the table.
# The Canterbury Tales - Geoffrey Chaucer
theString = "Whan that Aprille with his shoures soote,"
Instruction Result
theString[0] W
25
theString[11]
theString[28:32] hour
theString[5:9] that
Activity 2
Use this string from Green Eggs and Ham by Dr Seuss to complete the table.
# Green Eggs and Ham - Dr Seuss
guyIAm =
"I do not like green eggs and ham. I do not like them, Sam-I-Am."
Instruction Result
guyIAm[0:13:3] Ioole
guyIAm[31:28:-1] mah
(guyIAm[32:10:-2]) .a n genege
guyIAm[20:10]
."
print(guyIAm[5:25:5])
nire
Lesson Objective
Recap strings
26
Understand what is good programming practice
Activity 3
Complete the table to predict what each of the library string functions will output. Use the
following values as input. You may need to look some of the functions up in the online
documentation. Copy the code into your Integrated Development Environment (IDE) to check
your predictions.
lastName = "Fletcher"
firstName = "Alan"
address = "28 West End Lane"
postcode = "WC1V7BH"
Fletcher x
len(lastName) lastName = “Fletcher” 8
print(len(lastName))
firstName = "Alan"
firstName.isalpha() print(firstName.isalpha()) TRUE
lastName.upper() FLETCHER
address.isalpha() False
postcode.isalnum() True
address[0:2].isdigit() True
27
Paste the code here for the above flowchart (you completed this in the class)
28
Understand Constants, Variables and how to interpret and amend code
Here are some constants. Decide if there is anything wrong with the way they have been
declared and initialised. If so, write a line of code to fix it.
Constant What’s wrong with it? How would you fix it?
Make the code more readable by using white space, comments, and
meaningful identifiers.
29
XXX = "Goodbye"
n1 = 0
n2 = 0
theSum = 0
dif = 0
n1 = int(input("Enter a number: "))
n2 = int(input("Enter another number: "))
if (n1 > n2):
print(str(n1) + " is larger than " + str(n2))
theSum = n1 + n2
print("The sum is: ", str(theSum))
elif (n2 == n1):
print("Both numbers are equal.")
else:
print(str(n2) + " is larger than " + str(n1))
dif = n2 - n1
print("The difference is: " + str(dif))
print(XXX)
Make the code more readable by using white space, comments, and meaningful identifiers. You
my use your Integrated Development
#ASSIGNMENTS
Number 1 = 0
Number2 = 0
theSum = 0
dif = 0
#VARIABLE
Number1 = int(input("Enter a number: "))
Number2 = int(input("Enter another number: "))
#START OF GREETING
print(Hello)
30
print(str(Number1) + " is larger than " + str(Number2))
theSum = Number1 + Number2
print("The sum is: ", str(theSum))
elif (Number2 == Number1):
print("Both numbers are equal.")
else:
print(str(Number2) + " is larger than " + str(Number1))
dif = Number2 - Number1
print("The difference is: " + str(dif))
print(Goodbye)
Loops/Repetition
Activity 1
A program uses a count-controlled loop to count up to a maximum value. The output from
running this program is shown.
31
The code for the program is all jumbled up in the box below. Load the code into your Integrated
Development Environment (IDE) and arrange the lines to create a functional program.
Remember to use white space, comments, and indention to make your code readable.
MAX_VALUE = 6
count = 1
count = count + 1
# Constants
MAX_VALUE = 6
#Global Variables
count = 1
#Main Program
32
count = count + 1
25/3/24
Condition controlled loop
A controlled loop is a loop a loop that repeats for the amount of times that you set it to.,
Question 1
Add more selection statements so that the program outputs the different values shown in the
table.
Input Output
exit Goodbye.
Without nested
userChoice = ""
while userChoice != "exit":
userChoice = input("Enter your choice: ")
print("You chose:", userChoice)
if userChoice == "hello":
33
print("Hi! Nice to meet you.")
Variables - (global)
Variables - (Local)
Main —------
userChoice =""
Question 1
In this program, the user enters a number. A condition-controlled loop prints a counter statement
each time the program runs through the loop. The program also sums the numbers from 1 to the
number entered.
Here is the console output from the program.
34
The lines in the program are jumbled up in the box below. Arrange the lines of code to create a
functional program. You will need to do this in your Integrated Development Environment (IDE).
# ------------------------------------------------------------
# Global variables
# ------------------------------------------------------------
# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------
ANSWER
This is not correctly done, there is no loop (while) in this. Check the indentation and syntax.
Rearrange the code correctly
35
28/03/24
Learning objectives
RECAP
Global variables
Local variables
Using both
Subprograms
Arguments
36
A variable that is defined within a subprogram, thus only exists while that subprogram is
running
● Define the term ‘global variable’
A variable defined in the main program which can be accessed by any part of the
program
Justify using either or both
● Local variables are used most commonly as they are automatically created when using a
subprogram
● Global variables are used in the main program and passed as arguments into
subprograms
#---------------------------------------------
#Contant
#---------------------------------------------
#-------------------------------------
# Global Variables
#-----------------------------------------
# Main program
—----------------------------------
# Local variables
37
15th April 2024
Activity 1
Complete the table to give characteristics of local and global variables. Try to put the
information into your own words so that you fully understand the difference.
Term Characteristicsth
Global Global variables are variables that are declared outside of any
variables function or block of code and can be accessed to any part of the
program.
# ------------------------------------------------------------
# Global variables
# ------------------------------------------------------------
38
theChoice = 5
number = 99
# ------------------------------------------------------------
# Subprograms
# ------------------------------------------------------------
def showMenu ():
print ("Welcome to the random number generator.")
print ("1 - Even number")
print ("2 - Odd number")
print ("3 - Either will do")
print ("4 - Exit program")
choice = int (input ("Invalid choice. Enter a choice from the menu. "))
return (choice)
39
number = random.randint(1, 100) # Any
return (number)
# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------
showMenu ()
theChoice = getUserChoice ()
while (theChoice != 4):
number = genNumber (theChoice)
print ("Your number is: " + str (number))
# Go again
showMenu ()
theChoice = getUserChoice ()
Activity 2
Load ‘Activity_2.py’ into your development environment.
a) Give the names of two global variables.
theChoice = 5
Number = 99
pParity
Choice
40
number
In this activity, you are going to investigate the scope of local and global variables by
using the debugger in your integrated development environment. (Thonny - IDE)
● Look at the variables in the variable watch window. Remember, you may have to
select a ‘frame’, which represents the different scopes in existence at that
moment in time.
● Screenshot the variable watch window and paste it here.
41
● Check the variable watch window in the frame for the getUserChoice()
subprogram. You should now see that a variable named ‘choice’ has been
created.
● Screenshot the variable watch window for the subprogram and paste it here.
_________________________________________________________________________________________________
A variable is a container for storing information. The container resides in memory and gas a
label to identify it.
However, it is often necessary to store multiple pieces of information together in the same
container. A single variable on its own is usually not enough to do this.
Arrays
A data structure is a container that can hold several items at the same time. Many different
types of data structures are used in computer science.
42
43
22nd April 2024
Data Structures
+, -, /, * - operators
Operations -
1 - Add an item (append/add)
2 delete/remove an item
3 sort/order the items
4 copy the list
5 delete the whole list
Activity 1
Correct each of these lines of code so that they correctly create an array, using Python lists.
Continue
One-dimensional Lists
44
● An array is a data structure where all the elements are homogenous (i.e. have the same
data type).
● In Python, a list is used to implement the ‘array’ concept.
● Access each item in a list using indexing (in a similar way to strings).
● Use [ ] with index values starting from 0.
● Add, append, and delete items from a list.
● list.append(x) adds element x to the end of the list.
● list.remove(x) removes the first instance of element x from the list.
● del list[x] deletes the item at index x.
Highlight any of the billet points above to let me know if you do not understand anything.
Activity 2
Here are some arrays of data, stored as Python lists.
Complete the table to show the missing cells. One has been done for you.
Instruction Result
numPlants[0] 22
salad[1] cucumber
numPlants[4] 9
volumeLitres[:2] [3.7,2.5]
45
numPlants[5] error
volumeLitres[len(volumeLitres)-1] 1.9
windowOpen[len(salad)] False
salad[-2] Cucumber
Activity 3
For each instruction in column 1, predict the content of the array.
Check your answers by pasting the snippet into your programming environment, adding a
breakpoint, and then using the memory inspection tool.
One has been done for you.
nuts = []
nuts.append ("Hazelnut")
nuts.append ("Walnut")
nuts.remove ("Hazelnut")
46
ove ("Almond")
[0]
Activity 4
Here is the code for an existing list of named craters on the Moon. Type or load the code into
your Integrated Development Environment (IDE).
# ------------------------------------------------------------
# Global variables
# ------------------------------------------------------------
craters = ["Picard"]
# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------
# =====> Write your code here
47