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:
colours = ["Red", "Orange", "Purple","Pink"]
This makes it easy to loop through all the colours:
for i in range(4):
DrawShape(colours[i])
colours = ["Red", "Orange", "Purple","Pink"]
This makes it easy to loop through all the colours:
for i in range(4):
DrawShape(colours[i])
Using an Array
You refer to each item in the array by its index. For example:
t.pencolor(colours[0])
.. changes the pen to the colour "red".
t.pencolor(colours[1])
.. changes the pen to the colour "orange".
Note: array positions start at 0.
t.pencolor(colours[0])
.. changes the pen to the colour "red".
t.pencolor(colours[1])
.. changes the pen to the colour "orange".
Note: array positions start at 0.
Creating an Array of User Defined Colours
You can start with an empty array and then add your user's choice of colours. Create an empty array like this:
Use Input to ask the user for a colour. Then append ( add it to the end) it to your array:
Here's how to add another colour from the user:
To use the colour you must give the array position with square brackets:
Ready for a challenge?
The code above is fine, but what if you wanted to add 20 different colours? That's quite a lot of code. You can use for i in range to ask for a colour and then add it with far less code. If you are feeling brave.. try it and then check with your teacher!