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.
KS3, GCSE, A-Level Computing Resources
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.
from random import randint print (randint(0,100)) print (randint(0,100)) print (randint(0,100))
97 34 6
from random import randint students = [“Bob”, “Anna”, “Mo”, “Amal”] name_select = randint(0, 3) print students[name_select]
Bob ------ Amal ------ Bob ------ Anna ------
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.
shopping = ["Cheese","Apples","Milk","Goat"] print (shopping)
[‘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".
shopping = ["Cheese","Apples","Milk","Goat"] print (shopping[1])
Apples
You can add items to a List with the append() method.
shopping = ["Cheese","Apples","Milk","Goat"] shopping.append("Lemon") print (shopping)
[‘Cheese’,‘Apples’,‘Milk’,‘Goat’,‘Lemon’]
You can remove items from a List with the remove() method.
shopping = ["Cheese","Apples","Milk","Goat"] shopping.remove("Milk") print (shopping)
[‘Cheese’,‘Apples’,‘Goat’]
2 dimensional arrays are used to structure data in a table format.
stutests = [["Ahmed","23"],["Abu","46"],["Bushra","12"],["Hafsa","76"]] print (stutests)
[‘Ahmed’,‘23’],[‘Abu’,‘46’],[‘Bushra’,‘12’],[‘Hafsa’,‘76’]
stutests = [["Ahmed","23"],["Abu","46"],["Bushra","12"],["Hafsa","76"]] print (stutests[0]) print (stutests[3][0])
["Ahmed","23"] Hafsa
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.
RECORD scores studentname score1 score2 ENDRECORD class_score[0] = scores(“Ahmed”,23,28) class_score[1] = scores(“Abu”,46,39)