You are on page 1of 16

Introduction to Arrays

• Understand what is array.


• Learn to create, store, access
data from arrays.
What is array.
• Array is a variable with one name
that can have none, one or more
than one storage areas.
• Referring to individuals of storage
area is by using array name, square
bracket and index.
• Example: data[3], A[5]
To create array (1st approach)
and store values.
• M = “My name is Muhammad”
• N = M.split()

• Array created by using split


function. Now, N is an array with 4
storage areas. Referring to each
location by N[0],N[1],N[2] and N[3]
To create array (2nd approach)
and store values.
• M = [ 30, 20, 50 ]

• Array M created with 3 storage


areas with values are 30, 20 and 50.
Referring to each location by
M[0],M[1], and M[2]
To create array (3rd approach)
and store values.
• K = []
• K.append(33)
• K.append(20)

• Array K created with blank storage.


Then using append to create storage
area and store values 33, and 20.
Referring to each location by K[0], and
K[1].
How many storage are
there in array L?
• L = [0, 30]
• L.append(10)
• L.append(20)
• L.append(60)
Create, store, and access data array.
• A=[0,0,0]
• A[0]=20
• A[1]=30
• A[2]=A[0]+A[1]
• print(A[2])
Create, store, and access data array.
• A=[0,0,0]
• A[0]=eval(input("Width?"))
• A[1]=eval(input("Length?"))
• A[2]=A[0]*A[1]
• print("Area is ",A[2])
Why use array?
• Variable can be use for the index in
array. This provide flexibility in
accessing data storages.
• Example; A[n] where n can be
varied.
Example 1:
• F=[20,30,40,60]

• How to total up the numbers in


array F?
–T = 0
–For n in range(4):
– T = T + F[n]
–print(T)
Example 2:
• D=*“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”+

• print(“Days in a week”)
• for n in range(7):
• print(D[n])

• print(“Weekdays in a week”)
• for n in range(5):
• print(D[n])
Example 3(a): Total up 5 data.
t=0
for n in range(5):
data=eval(input("Data?"))
t=t+data
print("Total is ",t)
Example 3(a): Can separate?
for n in range(5):
data=eval(input("Data?"))

t=0
for n in range(5):
t=t+data
print("Total is ",t)

Cannot!
Example 3: But array can...
data=[]
for n in range(5):
data.append(0)

for n in range(5):
data[n]=eval(input("Data?"))

t=0
for n in range(5):
t=t+data[n]
print("Total is ",t)

s=""
for n in range(5):
s=s+" " +str(data[n])
print(s)
Example 4(a): Testing Multiplication of 8
no=0
for n in range(12):
no=no+1
question = str(no) + " x 8 = ?"
ans=eval(input(question))
if ans==no*8:
correct = correct+1
print("Correct: ",correct,"/12")
Example 4(b): Testing Random Multiplication of 8
no=[3,2,5,4,1,7,6,11,12,10,8,9]
for n in range(12):
question = str(no[n]) + " x 8 = ?"
ans=eval(input(question))
if ans==no*8:
correct = correct+1
print("Correct: ",correct,"/12")

You might also like