In this notebook, we'll investigate:
Loops! Loops allow us to repeat some code over and over again, either a certain number of times or until something happens.
The for
loop allows us to run some code a given number of times, and creates a variable for us that tells us how many times it's run so far:
for i in range(6):
print(i)
0 1 2 3 4 5
while
loop allows us to run some code until the something specific happens:n = 10
while n > 6:
print("n is still greater than 6...")
n -= 1
print("n is now equal to 6!")
n is still greater than 6... n is still greater than 6... n is still greater than 6... n is still greater than 6... n is now equal to 6!
my_favorite_colors = ["red", "green", "blue", "orange"]
print(my_favorite_colors)
print(my_favorite_colors[0])
print(my_favorite_colors[3])
my_favorite_colors += ["purple"]
print(my_favorite_colors)
for color in my_favorite_colors:
print(color)
Take a look at the following code:
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
This program performs the exact same action eight times. Boring, right? We can write it in a less tedious way by using a loop.
With a loop, we can ask the computer to run some of our code a certain number of times before moving on. The code we want to run repeatedly is called the "body" of the loop.
The following program uses a loop. Run it and notice how it has the same output as the one above!
for i in range(8):
print("Hello")
This is an example of a for
loop. It runs a block of code, print("Hello")
, eight times.
Like an if
statement, the for
loop has a body. The body is made up of all of the indented code that follows the line starting with for
. The computer will run all the statements in the body as many times as the loop says; in this case, 8.
You can have more than one statement in the body! What do you think the following program will print?
for i in range(4):
print("Hello")
print("World")
The computer executes all the code in the loop's body, then goes back to the beginning and runs it all again, as many time as we asked. This is why it is called a "loop": the computer steps through the body one by one, reaches the end, then circles all the way back to the beginning, until it has done this as many times as it needed.
Take a look at this program. What do you think it prints?
for i in range(4):
print("Hello")
print("World")
print("!")
Notice that the exclamation mark in the above program is printed once, only after the computer is done with the loop. The exclamation point is not part of the loop body. When the computer is done with the loop, it moves on to the rest of the statements.
Take a look at the loop below: what does it print?
for i in range(8):
print("Print me eight times")
print("Also print me eight times!")
Creating a for loop also creates a variable that tells us how far the computer is in the loop. We can call this variable the loop counter.
Did you notice the i
in the loops we've written so far? This is the name of the counter. We can use the counter like any other variable!
What do you think the code below will print?
for i in range(8):
print(i)
This might not have been what you expected!
The first time the loop runs, the counter has the value 0.
The second time the loop runs, the counter has the value 1.
The third time, it has the value 2.
...and so on, until the loop is over.
This means, as you saw above, that a loop which runs eight times will have a counter that starts at zero and ends at seven. This might be surprising! It is one example of why we often say computers like to start counting at zero rather than one.
The following code is a slight adjustment to the loop above. Can you guess what it prints?
for i in range(4):
print(i * 2)
The multiplication works, since we can treat the loop counter like any normal variable.
0
3
6
9
The body of the loop doesn't have to be just made of print statements; loops can execute any code at all, even if
statements or other loops!
Take a close look at the following loop. Here, we combine an if
and a loop together. Can you guess what it prints?
for i in range(8):
if i == 4:
print("My greetings.")
Let's walk through this one together.
First, we use for i in range(8)
to create a loop that runs eight times. The body of the loop is every indented statement after this, so the body is this code:
if i == 4:
print("My greetings.")
The body has an if
statement! And on top of the that, the if
has a body as well: a single print statement. We will only print the phrase "My greetings." if i
happens to have the value 4.
The computer will check this if
statement eight times. The first time, i
will have the value 0. The second time, it will have the value 1. Then 2, then 3, then 4, then 5, then 6, then finally 7. How many times does i
have the value 4? Just once! So the print only happens once.
The following loop uses a similar concept. What do you think it prints?
for i in range(6):
if i != 2:
print(i)
Here we print every number from 0 to 5, except 2!
When you're done with that, take a look at the following code:
my_number = 5
for i in range(3):
my_number += 1
print(my_number)
Run this code and see what it outputs. What is going on here?
Remember that loop bodies can run any code at all. We can even change variables in the body of a loop.
Here, we create a variable, then add 1 to it in a loop. That loop runs 3 times. After the first loop, my_number
will be 6, then it will be 7, then it will be 8, then the loop will end.
Effectively, this adds 3 to the variable, so we end up printing 5 + 3 = 8!
Before you move on, make sure you understand for
loops well enough to write a few on your own!
If you get stuck, look at the examples above. You may find it helpful to copy and paste some previous code. Of course, always feel free to ask the instructors for help.
Can you:
# Write your code here
If you were able to do one or more of these, show it off to the instructors!
while
¶There are actually two kinds of loops in Python!
We have looked at the for
loop, where we can specify exactly how many times we want our loop to go for.
Now let's look at the while
loop. With these loops, rather than saying how many times we want the loop to go for, we say that the loop should go until something happens.
The following code is an example of a while
loop:
n = 1
while n < 4:
print("Hello!")
n = n + 1
This loop is a quite a bit more complicated!
Like a for
loop, a while
loop has a body, but it also has a condition.
In a while
loop, we do not specify how many times the body should run - instead, we say that the loop should continue running until its condition becomes false.
In the above loop, the condition is n < 4
. This is a question that is either true or false; is n
less than 4?
The computer asks this question at the start of each loop. If the answer to the question is no - if it is false - the loop will stop! If the answer is yes, it will keep going. It is a lot like an if
statement that repeats by returning to the beginning when it is done.
Let's see another example:
n = 3
while n < 5:
print(n)
n = n + 1
Run this program and notice what it prints. It ends up just printing 3 and 4. Let's step through the loop together and see why this is:
First, the program sets the value of the variable n
to 3.
Then, it encounters the while
loop. Before running the body, it checks the loop's condition. Is n
less than 5? Yes! So, the loop body is run.
In the loop body, we first print the value of n
. This is 3, so the number 3 gets printed. Then, we increase the value of n
by 1. n
now holds the value 4.
Now that the body is done, the loop wants to run it again. So it checks the condition. Is n
less than 5? Yes, it stil is! So we run the body again. The number 4 is printed, and n
increases to 5.
The loop wants to run again, so it checks the condition again. Is n
less than 5? Oh - no, not anymore. So now the loop stops, and it is done!
Take a look at the following code. What do you think will happen?
n = 0
while n < 5:
print(n)
What is the condition of this loop? It is n < 5
. So, the loop will only stop when n
is not less than 5. But n
is always 0! We do not change the value of n
in the loop, so the loop never stops!
This is often known as an infinite loop, for obvious reasons. Generally, an infinite loop is not a good thing. They usually result from making a mistake in a while
loop - most often, from forgetting to change a variable in the loop.
You can stop an infinite loop by clicking on the program's play button again.
Before you move on, test your knowledge of the while
loop.
Try your best at these challenges - you can refer to anything else in the notebook or ask for an instructor's help.
Can you:
while
loop that prints something 16 times?while
loop that shows every number from 0 to 8, including 8?while
loop that shows every even number from 0 to 8, including 8?# Write your code here
Again, if you were able to do one or more of these, show it off to the instructors!
So far, we have seen variables that store exactly one thing: a single number, a single word, etc. However, variables can store more than one thing if we use lists!
my_friends = ["Sean", "Matt", "Hayden"]
print(my_friends)
The my_friends
variable is an example of a list! It stores 3 values instead of just one. We can create a list by writing multiple things down, then separating them with commas and surrounding all of them with square brackets.
When we print my_friends
, you'll notice it prints out everything in the list.
What if we want just the first friend? Or just the second one?
Each thing in a list has an index. This is a number describing where that thing is in the list - is it in the first position? The fourth?
The first item in a list always has index 0.
The second will have index 1.
The third will have index 2.
And so on.
Just like with a for
loop counter, the computer has started counting at 0! This can be very confusing, since the first item is NOT at index 1, but at index 0.
fruits = ["Banana", "Strawberry", "Lemon", "Mango"]
print(fruits[0])
This program shows how we can use an index to access the items in an array. Run it, and notice how just the first fruit in the list, Banana, is printed.
We can use this pattern with any list: if we have a variable that contains a list, typing the name of the variable will give back the entire list, but typing the name of the variable and a set of square brackets with a number inside will give back a single item in the list with the appropriate index.
Here are some more examples:
print(fruits[1])
print(fruits[2])
print(fruits[3])
print(fruits[2], fruits[3], fruits[0])
You can use the same technique to modify elements in the list:
fruits[3] = "Blueberry"
print(fruits)
This has changed the item at index 3 - the fourth item - into "Blueberry". It was "Mango".
We can also add entirely new items to a list, in a similar way to adding to numbers or words. The following program adds two new fruits to our list:
fruits += ["Lime"]
fruits += ["Blackberry"]
After adding these items, the fruits
list has 6 fruits in it. What happens when we try to access the element at index 6? This would be the seventh item, but as we know, there are only six of them...
print(fruits[6])
An error, of course! So be careful when directly accessing items in a list like this - if you give an incorrect index, the program will crash.
Be careful also when adding new items to a list. The square brackets around the item you want to add are required! The following program might look okay, but watch out, it is missing the square brackets around the 3:
numbers = [0, 1, 2]
numbers += 3
print(numbers)
numbers
array?Take a look at the two programs below. The first creates a list, and the second prints it out.
prime_numbers = [2, 3, 5, 7, 9, 11]
print(prime_numbers)
[2, 3, 5, 7, 9, 11]
Without touching the first program, can you:
As you have seen, the form of a for
loop is:
for i in range(10)
...of course, we can put any number in place of the 10.
So why have we been using the word range
? Well, roughly, range(10)
is actually a list of all of the numbers from 0 to 9!
How can we tell? Take a look at the following program:
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(i)
Notice that this does the exact same thing as the normal range
based for
loop!
for i in range(10):
print(i)
We can actually make the loop counter do whatever we want by replacing range
with any list! The loop counter variable will be given the value of each item in the list, in the order they are in the list.
For example: I can print every even number from 0 to 6 like this:
for i in [0, 2, 4, 6]:
print(i)
I can print every number from 0 to 6 backwards like this:
for i in [6, 5, 4, 3, 2, 1, 0]:
print(i)
I can print a bunch of totally random numbers:
for i in [26, 197420, -5]:
print(i)
I can even use the counter for words!
for i in ["Hello", "my", "friend!"]:
print(i)
Be careful about the formatting: there must be commas between each of the items! Notice that this program produces an error, because it is missing commas:
for i in [1 2 3 4]:
print(i)
for
loop? Can you print both words and numbers in the same loop?range
?for i in range(3):
print(i)
0 1 2
Whew! This is the end of day 3. Give yourself another pat on the back (literally, if you want.)
See if you can use what you've learned to complete a few of these challenges. You can look back at anything in the notebook and, of course, ask any of the instructors for help.
Can you write a program below that prints out every number from 0 to 10, including 10?
# Write your code here
(When you are done, your program should produce this):
0
1
2
3
4
5
6
7
8
9
Can you write a program below that prints out every even number from 10 to 20, including 20?
# Write your code here
(When you are done, your program should produce this):
10
12
14
16
18
20
The following program has a loop that prints every number in the numbers
list. Can you make this loop instead change every number in the list to 0?
numbers = [1, 2, 3, 4]
print(numbers)
for i in range(4):
print(numbers[i])
print(numbers)
[1, 2, 3, 4] 1 2 3 4 [1, 2, 3, 4]
(When you are done, your program should produce this):
[1, 2, 3, 4]
[0, 0, 0, 0]
By only changing the following loop, can you set numbers_contains_six
to True
if the numbers
list contains the number 6?
numbers = [1, 2, 3, 4, 5, 6]
numbers_contains_six = False
for i in numbers:
print(i)
print(numbers_contains_six)
1 2 3 4 5 6 False
(When you are done, your program should produce this):
[1, 2, 3, 4, 5, 6]
True
The program below has a really long list of numbers. To show you how big it is, it also prints the length of the list, which is how many elements it has. You can get the length of any list by using the len
command - look at the program below to see how it is used.
Can you extend this program to print the first and last elements of this list (without looking up what they are)?
very_long_list = [3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8]
print(very_long_list)
print(len(very_long_list))
Lists can contain other lists. These are sometimes called multi-dimensional lists.
Take a look at the following program. The list_of_lists
list contains 3 items, and each one of those items is a list itself! So, when we access the first element by using, say list_of_lists[0]
, the resulting item is also a list.
list_of_lists = [[1, 1], [2, 3, 5], [8, 13]]
print(list_of_lists)
print(list_of_lists[0])
print(list_of_lists[1])
print(list_of_lists[2])
Knowing this, can you extend the program to also print the last element of each of the 3 lists inside of list_of_lists
?
If you managed to complete some or all of these, give yourself a pat on the back and show the instructors your awesome work!