1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 4. Data Structures


Lesson Objective

  • Learn why and how to generate random numbers.
  • Understand the concept of a 1 dimensional array, a 2 dimensional array and a record.

Lesson Notes

Random Numbers

To use the random number function in Python you must define which module you would like to use defining the "random" module and importing the "randint" function.

Code:

from random import randint
print (randint(0,100))
print (randint(0,100))
print (randint(0,100))

Cmd Output:

97
34
6

Code:

from random import randint
students = [“Bob”, “Anna”, “Mo”, “Amal”]
name_select = randint(0, 3)
print students[name_select]

Cmd Output:

Bob
------
Amal
------
Bob
------
Anna
------

1 Dimensional Array (Lists)

A 1 dimensional array is used to store multiples items of data. A List can also be stored in a Variable. Items in a List do not need to be the same data type.

Code:

shopping = ["Cheese","Apples","Milk","Goat"]
print (shopping)

Cmd Output:

[‘Cheese’,‘Apples’,‘Milk’,‘Goat’]

To refer to just one item in the list, you would refer to its index position. Each item is given a number. The first item is referred to as position "0".

Code:

shopping = ["Cheese","Apples","Milk","Goat"]
print (shopping[1])

Cmd Output:

Apples

1 Dimensional Array (Adding Items)

You can add items to a List with the append() method.

Code:

>
shopping = ["Cheese","Apples","Milk","Goat"]
shopping.append("Lemon")
print (shopping)

Cmd Output:

[‘Cheese’,‘Apples’,‘Milk’,‘Goat’,‘Lemon’]

1 Dimensional Array (Removing Items)

You can remove items from a List with the remove() method.

Code:

shopping = ["Cheese","Apples","Milk","Goat"]
shopping.remove("Milk")
print (shopping)

Cmd Output:

[‘Cheese’,‘Apples’,‘Goat’]

2 Dimensional Array

2 dimensional arrays are used to structure data in a table format.

Code:

stutests = [["Ahmed","23"],["Abu","46"],["Bushra","12"],["Hafsa","76"]]
print (stutests)

Cmd Output:

[‘Ahmed’,‘23’],[‘Abu’,‘46’],[‘Bushra’,‘12’],[‘Hafsa’,‘76’]

2 Dimensional Array - Indexing

Code:

stutests = [["Ahmed","23"],["Abu","46"],["Bushra","12"],["Hafsa","76"]]
print (stutests[0])
print (stutests[3][0]) 

Cmd Output:

["Ahmed","23"]
Hafsa

Records

The problem with using arrays to store data is that they are hard to read and are Homogeneous data structures - meaning they hold only one data type.

Record are Heterogeneous data structures and allow you to store multiple data types. Once the data is captured as a record, it can be stored in an array.

Code:

RECORD scores
    studentname
    score1
    score2
ENDRECORD
class_score[0] = scores(“Ahmed”,23,28)
class_score[1] = scores(“Abu”,46,39)

Cmd Output:



3