Lists in Python.
In the above program, I have made a list and then said to print all of the strings in the list five times.
colors is the name of the list, and every string in the straight brackets is an item in the list.
for x in range(5): is a for loop. This is saying, for all x values in a range of 5 values, do the things indented under the loop. So, when x is 1, it does the indented commands, and then x becomes 2, and does the indented commands, and so on until after it goes through the indented commands when x is 5.
In computer science, we start counting at 0. So, colors[0] is referring to the item in the list colors at index 0. Index zero is the first item, in this case the string 'Red'.
Note that after the list, there is a semicolon. This is just part of the Python syntax. There's also a colon after the for loop, which is there for the same reason. You also need a colon after defining functions.
If you wanted to add an item to the end of the list you made (later in the code), you would use append.
When I say print colors, that means I want to print the list, not the items in the list.
Now, I don't really think I like how I've printed the items .. so I'm going to change it.
Uh-oh ..
If you want to put something into your list, but not at the end, you'll use insert. If you don't know the index you want to insert the new item, you'll need to use index.
So, I decided I wanted the new color to go before 'Orange', so I found where 'Orange' was, and then inserted 'Teal' at that index. When I set orange equal to colors.index('Orange'), orange was set to the index number. From above, it's shown that 'Orange' was at index 2, or colors[2], so now, 'Teal' is at colors[2], and 'Orange' is now at colors[3].
Farewell pic :
My best friend and I got matching cases and keychains at Claire's.
~ Cici
No comments:
Post a Comment