When you have a series of commands that you want to repeat, you're going to want to use a loop. Each time a loop runs, we call it an iteration.
There are two types of loops.
Loops that repeat based on a number - for loop
Loops that repeat based on logical truth - while loop
The for loop is used when you need to repeat your code based on a certain number of times. This is pseudo code:
NOTE THE FOLLOWING IS PSEUDO CODE. IT WILL NOT RUN.
for counter in range(start, stop):
cool stuff happens here, as many times as the loop runs
look, a 2nd line of cool stuff
and finally, a line of code OUTSIDE the for loop
What do you notice?
for loopcounter in range(0, 5):
print('Hello')
What happened in the loop? The for loop needed a counter, that variable was called loopcounter. The for loop ran from the numeric range, 0 to 5. Each time it looped, the print() executed.
Check: to see if the counter variable is in the range
Do: do each indented line of code in the loop
Math: typically the counter variable goes up by one.
for loopcounter in range(0, 5):
print(loopcounter)
What happened in the loop? The for loop ran five times. The amount of loops was controlled by the range(). Each time the loop ran, the variable loopcounter was printed with print(). Did you notice where the number started and left off? Most people, mistakenly, expect numbers to start at 1, not 0.
Let's look at helping those folks out in the next example.
for loopcounter in range(1, 6):
print(loopcounter)
That output looks better, doesn't it? But what is it telling us about numeric ranges?
for counter in range(1, 11):
print(counter * 5)
The data structure that I'm going to use in the next example is called a list. Don't worry about lists for now. Let's just use it.
Our first for loop examples have Python iterating across a range of numbers, using range(). Python can also loop across a set of data. It does all the counting for you:
caf_specials = [ 'breakfast sandwich', 'milk', 'rice', 'pizza', 'salad', 'fish and chips' ]
for i in caf_specials:
print(i)
What happened? Python took each item in the list, and held it in the variable i.
As the loop, looped, the print() printed whatever was in the variable i.
The loop ran for as many times as there were things in the list.
Python will do the same with a string.
my_string = "This is the most interesting sentence I could think of."
for i in my_string:
print(i)
At this point in the course, for loops depend on the range(). It stands to reason that we should explore this built-in function.
#range([start], stop[, step])
#start: Starting number of the sequence.
#stop: Generate numbers up to, but not including this number.
#step: Difference between each number in the sequence.
for i in range(5): # only stop value provided
print(i)
print('')
for i in range(0, 5): # start and stop value provided
print(i)
print('')
for i in range(5, 0, -1): # start and stop and negative step value provided
print(i)
print('')
for i in range(0, 6, 2): # start and stop and step value provided
print(i)
A loop can be placed in another loop. This is called a nested loop.
for outer_loop_counter in range(0,4):
print('OUT')
for inner_loop_counter in range(0,4):
print('In')
What do you notice?
The outer loop seems to run once, then the inner loop runs several times, and then the outer loop runs, then the inner loop runs several times.
Let's look at at that previous example, but modify the print(), so that you can see what's happening to the counters.
for outer_loop_counter in range(0,4):
print('OUT', outer_loop_counter)
for inner_loop_counter in range(0,4):
print('IN', inner_loop_counter)
Notice that the inner loop is reset?
What would a student's school week look like in a nested loop?
for day in range(0,5):
print('A School Day Begins')
for period in range(0,4):
print('A School Period')
print('A School Day Ends')
While loops are also known as conditional loops. While require a condition to be true. This condition is also known as a test.
Before we start learning about while loops, I'm going to show you how to stop an infinite loop. CTRL-c remember that.
x = 5
while x == 5:
print(x)
Well, that happened? That's a lot of 5's... Hope you remembered CTRL-c!
The while loop was set to run as long as x == 5.
If the operator == is confusing you, please take a moment to look at the operators note.
It turns out that x was set to 5 before the the loop, and x will remain 5 until, forever.
Let's try that again
x = 5
while x > 0:
print(x)
x -= 1
In this example, x was set to 5 before the loop.
If the operators > or -= are confusing you, please take a moment to look at the operator note.
The while loop was set to run as long as x was greater than 0.
But, if you look in the loop, we are subtracting 1 from x on each rotation. Eventually, we get to the situation where 0 > 0 and the loop stops because the condition is false.
Sometime when I am talking about while loops, you'll hear me reference a flag. What I mean is a boolean that controls the while loop. Here's an example:
flag = True
while flag == True:
print('Hello')
userinput = input('Please input the word STOP, to stop this loop: ')
if userinput == 'STOP':
flag = False
else:
print('I guess this is not going to stop')
The next lesson will have code snips of loops in action!
As we have already discovered, for loops work well when your loops are based on counting, and while loops are very effective when you have a boolean expression (True or False).
How can we manage our loops based on other input?
userInput = input('Please enter a number: ')
userInput = int(userInput)
for counter in range(0, userInput):
print(userInput)
z = True
while z:
print('Hi')
userInput = input('Please type Q to quit ')
if userInput == "Q":
z = False
w = input('Please type in a number: ')
w = int(w)
for w in range(0, w):
print(w)