0% found this document useful (0 votes)
13 views

Topic 2_ Programming (i-GCSE)Computer Science

The document outlines a computer science curriculum focused on developing algorithms, pseudocode, and flowcharts, covering data types, boolean operators, and programming constructs such as sequence, selection, and iteration. It includes various tasks and examples for students to practice creating flowcharts and pseudocode for real-world scenarios, along with homework assignments to reinforce learning. Additionally, it introduces Python programming concepts, emphasizing the importance of syntax, error handling, and the use of integrated development environments (IDEs).

Uploaded by

artur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Topic 2_ Programming (i-GCSE)Computer Science

The document outlines a computer science curriculum focused on developing algorithms, pseudocode, and flowcharts, covering data types, boolean operators, and programming constructs such as sequence, selection, and iteration. It includes various tasks and examples for students to practice creating flowcharts and pseudocode for real-world scenarios, along with homework assignments to reinforce learning. Additionally, it introduces Python programming concepts, emphasizing the importance of syntax, error handling, and the use of integrated development environments (IDEs).

Uploaded by

artur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

i-GCSE

Computer Science
29th November 2023
Lesson 1
●​ Developing Algorithms and Pseudocode​

Learning Objectives

1_ Data types
Boolean - 2 outcomes. for example: yes or no

Integer- whole numbers only


Real or floating point- numbers have a decimal part

String - Used to represent text, it is a collection of characters

Character- a single letter or symbol

2 Boolean operators - =, < > /

3 - Algorithms, Pseudocode and Flowcharts

Algorithm -a process or set of rules to be followed in calculations or other problem-solving


operations, especially by a computer.

Pseudocode - is a kind of structured English for describing algorithms.

Flow charts- - diagram representation of the above 2

*​ (Multiply)
(==) Equal to
+​ (Concatenate)

4- flowcharts and algorithms Sequence

​ Sequence

1
14th December 2023
(2 hour lesson 2 and 3)

Flowcharts and Algorithms

Programming constructs

Sequence- and order in which something is done


Selection- If elseif else ( branch depending on condition)
Iteration (loop)- instructions that need repeating
-​ For next
-​ while
-​ Do until (timer with conditions)

Computer systems consist of input, process, and output.

Algorithms - a set of instructions for solving a problem

Pseudocode - mi language description of the steps in an algorithm or another system.

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.

5475 days = 15 years

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.

The flow diagram for the game is shown below.

(a) Complete the statement at A. 0


(b) Complete the statement in B. <
(c) Complete the statement at C. add ballon score (1) to the origin number
(d) Complete the line and label at D. as above

5
(e) ​ Add a flowchart box at the bottom to display the player’s score. Display player score in
output box

(a) Complete the statement at A. balloonScore 0


(b) Complete the statement in B. Time < 60
(c) Complete the statement at C. balloonScore balloon score + 1
(d) Complete the line and label at D. As above
(e) Add a flowchart box at the bottom to display the player’s score. As above.

Task 2 answer

Task 3 - Create a flowchart for an algorithm that finds the maximum of three numbers.

6
INput — Process — Output

Input - num 1 (67)

Input - num 2 (74)

If num 1 > num 2

Output num 2

If num 1 < num 2

out put num 2

Output num 2

OUTPUT + HIGHER number

Input number 2> input number 3> input number 1

21st December - Thursday 4pm-5pm

Lesson 4 - Flowcharts and Algorithms (conti)Starter - Recap

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”.

Complete the flowchart for the barriers in the amusement park.

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.

Item number Item description

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… ​

5>2​ TRUE ​ 80 < 80 ​ FALSE ​

24 + 1 <= 25 ​ ​false 16 – 1 < 16 ​ ​true

5^2 == 25 ​ ​true 3 >= 3 ​ ​false

5 != 3 ​ ​true "Hel" + "lo" ​true


== "Hello" ​

2 == '2' ​ ​false age == age + ​false


1​

Does this make sense?

is a Pseudocode for kind structured English describing of algorithms


Pseudocode is a kind of structured English for describing algorithms (Grammar english
language)

Code - syntax (grammar of programming language)

12
Indentation (spacing)
Colon :
Semi colon ;
If then else s
tatements
Loops - for next, while end while

Programming constructs

Sequence- and order in which something is done


Selection- If elseif else ( branch depending on condition)
Iteration- instructions that need repeating (loops)

03/01/24

Objectives

1)​ How to start using PYTHON in Windows


2)​ Recap on data types, boolean operators
3)​ Write algorithms in pseudocode involving sequence, selection and then write the
code in Python using the correct syntax

13
Complete the flowchart to show the following
pseudocode
mealCost = 4.00
drinkCost = 2.00
total = mealCost + drinkcost

Explain what is input, process and out in the above


How can output shown/written

Programming constructs

Sequence- and order in which something is done


Selection- an IF statement is a type of selection statement ( branch depending on
condition)
Iteration- instructions that need repeating

What i've learned today.

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

6.​ Recap shapes of flow chart

14
Homework - To be completed before next lesson

Please complete the flowchart above.

1) Write a statement of pseudocode to subtract discount from markedPrice to give


salePrice
2) Write a statement of pseudocode to change the value stored in total to include VAT
(at 20%)
3) Write all the keywords and the meaning in the Google document where I have asked
Artur to write class notes.

Make a list of all keywords we have covered so far and write its meaning with examples.

18th January 2024



Flowchart Algorithm Pseudocode Code

1 step 1 enter marked price Input marked price x #INPUT //Comment


Step 2 multiply by 0.9 0.9 marked_price =
Step 3 total discounted price float(input("Enter the marked
output discounted price: "))
price discount_percentage =
float(input("Enter the discount
percentage: "))

# 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

HW - 18th January 2024

1)​ Explain in your own words what you learned today?


that the # is for comments

2)​ How you do write a pseudocode and code for input and output

3)​ Write a single statement to do each of the following:

•Display a prompt “How old are you?”


Accept an answer from the user

16
Assign the answer to a variable called age

•Display a prompt “Press Enter to continue”


When the user presses Enter, continue to the next statement

Continue writing statements to introduce yourself

*
23rd January 2024

Learning objective

Keywords

Computational thinking- the use of computers to solve problems

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 ​

2nd February 2024


Recap - on programming contructs, algorithm design and pseudocode

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

< - less than

> more than

== (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

Practice exam style questions


Q1) Write a program to print out ‘Hello World’ ​
Q2) Write a program that writes your name on the screen and say hello​
Q3) Complete the table below. Predict what the code snippet will output, then write what
happens when you type the code into the interpreter

20
Predictions,
1. 15
2. 9
3 .4.4
4. 4
5. 25
6. 88

Please copy and paste your answers here

2/11/2024

Input —> int( favorite_number


Input —>int(users_age

output →> (favorite_number*users_age)+(favorite_number+users_age)

Input –) (number_one
Input –) (number_two

20th of february

Learning objectives for today

-meaning of program
-IDE integrated development environment to work with a python program
-use arithmetic operators (<,>,=,!=, ==, *,+,-,/)

Program- programs are instructions given to computers to get them to functions.

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)

22nd February 2024

Sequences and errors​

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)​

27th february 2024

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?

In the program below explain what is happening?


What are the different sections of the program depicted? Explain in
your own words

A program that uses a library (random) and we are also using


lists [ ]

Find the code below:


# imported a library
import random

# using LISTS
adjectives = ["silly", "goofy", "absurd", "ridiculous", "ludicrous"]
nouns = ["noodle", "muffin", "banana", "pickle", "sock"]

# for loop is used


for _ in range(5):
insult = f"You {random.choice(adjectives)}
{random.choice(nouns)}!"
print(insult)

Did you know?


The double star operator, denoted by (**), is an arithmetic operator in
Python often used for exponentiation

23
Homework - 27th February 2024

Answer the following questions:

Q1) Show with an example how you take input and create output.​
Using input() and print() to make a responsive program.​

Q2) Define the term 'runtime error’.​

Q3) Find and fix runtime errors. Show with a help of an example

Q4 What are primitive data types?

4th March 2024

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)

print("Your PIN is", pin)

24
3/7/24

Use string indexing


Using string manipulation factors

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

theString[18:26] with his

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

14th March 2024

Lesson Objective

Recap strings

Learn about operators used in if elif and else

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"

Code Prediction Actual output

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

28 West End Lane


address + " " + postcode
WC1V7BH

lastName + firstName FletcherAlan

27
Paste the code here for the above flowchart (you completed this in the class)

Check HW in the homework doc

25th March 2024

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?

sidesOfDice = 6 It is not all caps SIDES_OF_DICE

YES = “Y” Nothing is wrong with it

Bicyclewheels = 40 It is not all caps BICYCLE_ WHEELS

P = 3.14159 It should be “PI” PI

MAX_SWIMMERS = 25 Nothing is wrong with it

h = “SOS” It should be “HELP” HELP

Here is the code for a simple program.

Make the code more readable by using white space, comments, and
meaningful identifiers.

You may use your Integrated Development Environment (IDE).

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

#GREETINGS AND GOODBYE


Hello= "Hello"
Goodbye = "Goodbye"

#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)

if (Number1 > Number2):

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

●​ use repetition (condition-controlled loops) in algorithms​


●​ use repetition (condition-controlled loops) in code​
●​ use repetition (condition-controlled loops) in flowcharts.

Let’s imagine you wanted to print ‘hello world’ ten


times.

Write a code for this

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

while (count <= MAX_VALUE):


print ("loop count:" + str(count) + "out of" + str(MAX_VALUE))

count = count + 1

# Constants

MAX_VALUE = 6

#Global Variables

count = 1

#Main Program

while (count <= MAX_VALUE):


print ("Loop count: " + str(count) + "out of " + str(MAX_VALUE))

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

hello Hi! Nice to meet you.

exit Goodbye.

joke Where does the Easter Bunny go when he


needs a new tail? To a re-tail store!

song Row, row, row your boat.

None of these Try again.

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 =""

serChoice = input("Enter your choice no caps pls: ")


print("You chose:", userChoice)
if userChoice == "hello":
print("Hi! Nice to meet you.")
elif userChoice == "song":
print("row, row, row, your boat")
elif userChoice == "joke":
print("why did the skeleton cross the road? to go to the body
shop!")
elif userChoice == "exit":
print("Goodbye")
else:
print("try again")

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​
# ------------------------------------------------------------​

count = int(input ("Enter a number of times to loop (1-5)"))


startCount = 0
count = 0
total = 0
print("Loop count: " + str(count))
total = total + count
while (count > 0):
startCount = count
count = count - 1
print("Sum of numbers " + str(startCount) + " to 1 is: " +
str(total))

ANSWER

count = int(input ("Enter a number of times to loop (1-5)"))


startCount = 0
count = 0
total = 0
print("Loop count: " + str(count))
total = total + count
startCount = count
count = count - 1
print("Sum of numbers " + str(startCount) + " to 1 is: " +
str(total))

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

●​ Define ‘local variable’


●​ Define ‘global variable’
●​ Justify using either both
●​ Explain that the ‘range’ function a generates sequence of numbers
●​ Use the iteration for to process every item in a one dimension data structure

Local variable should be:


●​ Used as your first choice, always
●​ Use inside sub programs

Global variables should b e


●​ used as sparingly as possible
●​ Used only in main program
●​ Passed as arguments into a subprogram when a subprogram needs to change
them.

RECAP

Global variables

Counting loops (properly)

Local variables

Using both

Subprograms
Arguments

You have learnt

●​ Define the term ‘local variable’​

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

Basic structure of any program you write

#---------------------------------------------

#Contant
#---------------------------------------------

#-------------------------------------

# Global Variables

#-----------------------------------------

# Main program
—----------------------------------
# Local variables

37
15th April 2024

Recap Local and Global variables

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

Local Variables that are local to a subprogram. These variables


variables can only be accessed to a certain part of the program.

Lifetime limited to scope; each local variable is only used


once.

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.

Load ‘Activity_2.py’ into your development environment.


Activity 2
# ------------------------------------------------------------
# Import libraries
# ------------------------------------------------------------
import random

# ------------------------------------------------------------
# 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")

def getUserChoice ():


choice = ""

choice = int (input ("Make a choice from the menu. "))


while ((choice < 1) or (choice > 4)):

choice = int (input ("Invalid choice. Enter a choice from the menu. "))

return (choice)

def genNumber (pParity):


number = 0

number = random.randint (1, 100)


if (pParity == 1): # Need even
while (number % 2 != 0):
number = random.randint(1, 100)
elif (pParity == 2): # Need odd
while (number % 2 != 1):
number = random.randint(1, 100)
else:

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 ()

print ("Thank you. Goodbye.")

Activity 2
Load ‘Activity_2.py’ into your development environment.
a)​ Give the names of two global variables.

theChoice = 5

Number = 99

b)​ Give the names of three local variables.

pParity

Choice

40
number

18th April 2024

Continue Local and Global variables

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)

a.​ Load ‘Activity_2.py’ into your development environment.


b.​ Run the code to see what it does.
c.​ Set a breakpoint on line 50.

●​ 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.

d.​ Set a breakpoint on line 23.


●​ Resume execution until the next breakpoint.
●​ Check the variable watch window in the main program. You should still see the
same variables you saw in the previous step.
●​ Check the variable watch window in the frame for the getUserChoice()
subprogram. You should see that no variables have yet been created.
●​ Single step your debugger to line 25.

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.

_________________________________________________________________________________________________

What is a variable? 18/4/24

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.

An array is one kind of structure

It contains a number of items grouped together. It is named using a single identifier.

42
43
22nd April 2024

Data Structures

What are operations that can be performed on Lists/Array?

+, -, /, * - 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.

fruit = ["grapes "pear "apple "orange] ​


lengthMetres = 2.45, 1.88, 2.93 ​
countSweets = [1034, 2821 1567, 1336, 1978] ​
concertTrip = False, True, True, True, True] ​
newBooks = [,,,]

Complete these activities

25th April 2024

Continue

One-dimensional Lists

So far you have learnt:

●​ Define the term ‘data structure’.​


●​ A collection of data stored under one identifier.​
●​ Define the terms 'array’ and 'list’.​

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.

salad = ["tomatoes", "cucumber", "pepper", "lettuce"] ​


windowOpen = [True, True, True, False, False] ​
numPlants = [22, 13, 11, 16, 9] ​
volumeLitres = [3.7, 2.5, 3.1, 2.8, 1.9]

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

windowOpen[2:4] True, False

volumeLitres[:2] [3.7,2.5]

[:2] is a slice notation which specifies a range of


elements to extract from the sequence. In this
case, it means to take all elements from the
beginning up to (but not including) the element at
index 2

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 = []

Instructionrediction Screenshot before Screenshot after

nuts.append ("Brazil") [“Brazil”]

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

Amend the code to complete these tasks: ​

●​ display the list


●​ add “Thebit”
●​ add “Metius”
●​ add “Humboldt”
●​ display the list
●​ remove “Metius”
●​ add “Copernicus”
●​ display the list
●​ delete the second item in the list
○​ hint: what position is that?
●​ display the list
●​ add “Aristoteles” to the front of the list
○​ hint: look up list.insert() in your Python documentation
●​ display the list.

47

You might also like