Data types are important when programming. The computer has to know whether to expect numbers, text, or other types of values. We studied a little about how data is stored during the computer systems topic.
# This is an integer
myage = 15
# This is a real(float) number
price = 0.99
# This is a string
faveSubject = "Computing"
# This is a character (Python does not have a dedicated character data type, so characters are stored as strings of length 1.)
firstInitial = "F"
# This is a Boolean
isStudent = True
# When you input a string...
name = input("Please enter your name")
# When you input an integer number, use int( )
age = int(input("Enter age"))
# When you input a real number, use float( )
price = float(input("Enter price"))
The 1-D array data structure is used in a program to store a collection of data objects of the same type.
Let’s say we have a program that asks for 3 test scores, adds them together, and prints out the total.
It could probably start with something like this:
score1 = int(input("Please enter first score"))
score2 = int(input("Please enter second score"))
score3 = int(input("Please enter third score"))
What happens when we need a program that asks for 20 scores? Or 100? We could write out every variable, but it would be a very long program, and the chance for mistakes is high. Instead, we need a list...
This is called an array. Where a normal variable stores data in one memory location, an array reserves a whole set of memory locations, one after the other. You can think of an array like a list:
An array is like a variable that stores multiple values. We start counting the elements from 0 (instead of 1).
So element 0 in that array is 15, element 1 is 20, and element 7 is 19.
Like variables, arrays have data types (a string array, an integer array, a Boolean array, etc.)
When you see the term data structure, this refers to a variable or an array.
# An array of five empty strings
pupilnames = [str]*5
# An array of five integers, all set to 0
scores = [int]*5
# An array of ten real numbers
prices = [0.0]*10
# An array of nine scores out of 20
scores = [15, 20, 19, 18, 17, 20, 16, 19, 12]
# Get the fourth element from the array
iwant = scores[3]
We know that arrays are used for a list of data, to reduce repetition (having separate variables for score1, score2, all the way to score100…) Likewise, we know that loops are used to cut down on repetition in our lines of code.
We can use a loop to traverse the array - that means, to travel through it, or loop through it.
# An array of seven names
names = [“Dopey”, “Grumpy”, “Doc”, “Bashful”, “Sneezy”, “Sleepy”, “Happy”]
# The array elements are numbered from 0 to 6
# Loop from 0 to 6 and print the name
for counter in range(0, 7):
print(names[counter])
names = [str] *20
scores = [int] *20
for counter in range(0,20):
names[counter] = input("Enter the name: ")
scores[counter] = int(input("Enter their score: "))
print(names)
print(scores)