In the code below there are two variables: order and quantity. Input is used to get data from the user. Once the data is stored it can be used. For example below print is used to display variable name.
What is an Array?
A variable stores on piece of data ( e.g. colour = "red"). An array stores several pieces of data together:
Days = ['Sunday', 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
Days = ['Sunday', 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
Using an Array
Arrays first position is zero. This is called the array index. Access the array by giving its name followed by square brackets. In the brackets type the index for the desired item:
print Days[0] will be output "Sunday"
print Days[1] will be output "Monday"
print Days[0] will be output "Sunday"
print Days[1] will be output "Monday"
Efficiency - Writing fewer lines of code
Data in an array can be processed together. This often results in you having to write fewer lines of code. In the example below a for loop is used on lines 4 and 5 to display each day in turn. This is much shorter than displaying seven days one at a time.
In the function below the array position is directly accessed at the desired position using the day num. The index position for the return statement is one less than the day number ( Sunday is day 1 but it is position 0 in the array).