Lesson 3: Lists and Loops
A list is another way to store things, but it can hold a lot of things. Lets look at a few examples:
- Lets say our parents want to make cookies and we need to create a shopping list
- Think of the things you need to make cookies: Milk, eggs, sugar, chocolate chips, flour.
- See how we wrote that sentence above? we separated each item we need with a comma. Writing code is very similar:
shoppingList = ["Milk", "Eggs", "Sugar", "Chocolate chips", "Flour"]
Lets print that list out…
That will print out:
['Milk', 'Eggs', 'Sugar', 'Chocolate chips', 'Flour']
Now lets find out how to print specific items in our shopping list. Each item in our list has its own index. An index is a number used to get that item from the list. Lists always start with the number 0.
0 1 2 3 4 ['Milk', 'Eggs', 'Sugar', 'Chocolate chips', 'Flour']
So to print out the first item from our shopping list, we would write:
print(shoppingList) which would print
- We access the items by using the name of our list shoppingList and putting the index of the number we want inside [ ]
- So to print out Sugar we would do
Now how would you get our program to print out Flour ?
Answer: To print out
Flour we would do
Lets practice and teach you about Loops!
- A loop is a way for the program to do something over, and over, and over again
- We use loops to do repetitive tasks for us so we don’t have to
- Take a look at the code below.
- Add some of your favorite movies to the favoriteMovies list
Let’s show you your first loop
for movie in favoriteMovies: print(movie + " is one of my favorite movies")
This loop says … for each
movie in our
favoriteMovies list we want our computer to say “_____ is one of my favorite movies”
Press the play button to see what happens!
Previous Lesson - Lesson 2: Variables
If someone tries to fork and edit it online in that article it throws an error