Hello everybody,
It’s Michael, and today’s Python lesson will be on loops. Like Java, Python also has loops, but while Java has three main types of loops, Python only has two-while and for. There is no do-while loop in Python.
Let’s start by discussing the while loop. The Python while loop works the same as its Java counterpart since both loops will keep running WHILE a certain condition is true. Here’s a demonstration of a Python while loop:
x = 10
y = 1
while (y <= 6):
print(x**y)
y += 1
And here’s the output:
10
100
1000
10000
100000
1000000
In this while loop, successive powers of 10 are printed as long as y is less than or equal to 6; y is also incremented by 1 with each iteration of the loop. In other words, the first 6 powers of 10 (from 10^1 to 10^6) will be printed.
One thing to keep in mind is that, even though Python while loops work the same as their Java counterparts, the syntax between the two while loops differs. However, the difference is fairly minor, as Python would use a colon to denote the loop, while Java would use a pair of curly brackets.
Now, let’s make things a little more complex by adding the break statement. Here’s a sample program:
x = 1936
while (x <= 2020):
print(x)
x += 4
if (x % 7 == 0):
break
And here’s the output:
1936
1940
1944
1948
1952
1956
One thing to remember with the break statement is that it gives the loop another condition to evaluate. Loops with a break statement will keep running until either one of two conditions has been met. In the example above, the program will keep printing numbers (starting from 1936) and increasing them by 4 after each iteration until either 2020 (or the closest possible number to 2020) OR a number evenly divisible by 7 has been reached. In this case, 1960 would be the first number evenly divisible by 7, but the program will stop printing at the closest possible number-1956.
Now let’s try implementing a continue statement:
x = 2
while (x <= 20):
x += 2
if (x == 10):
continue
print(x)
And here’s the output:
4
6
8
12
14
16
18
20
22
Unlike the break statement, the continue statement won’t stop running a loop if a certain condition is met. Rather, if a certain condition is met, the continue statement will skip a certain iteration of the loop but then continue to run the loop. In this example, x is 2 and will keep increasing by 2 until x reaches 20. However, the continue statement says if (x == 10) continue. This means that 10 will not be displayed in the final output; rather, the program will jump from 8 to 12, as it was told to skip 10.
Now I’ll discuss for loops in Python. They are similar to their Java counterparts, except that they don’t require an indexing value to be set beforehand.
- In case you’re wondering, the
xin all of mywhileloop examples is an indexing variable. In Pythonwhileloops, an indexing variable acts as a “guide” by telling the loop where to start.
Another difference between Python for loops and their Java counterparts is that Python for loops are mostly used just to run through sequences of characters or Strings while Java for loops have more mathematical capabilities. In other words, with Java for loops, you’re able to do calculations with each iteration, but that isn’t possible with Python for loops. However, you can run through basic number sequences with Python for loops, which I will explain later.
Let’s demonstrate a basic Python for loop:
for y in “Michael”:
print(y)
And here’s the output:
M
i
c
h
a
e
l
In this program, I have a basic for loop that will run through all the letters in my name-Michael-and print out each letter one by one.
Notice that the syntax for Python for loops is much simpler than for their Java counterparts. In Java, you would need one line with three different statements whereas in Python, you only need one line for one statement, which always goes like for _____ in _____ followed by the body of the loop.
Now let’s try adding a break statement with a for loop:
teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”]
for y in teams:
print(y)
if (y == “76ers”):
break
And here’s the output:
Heat
Cavaliers
Timberwolves
76ers
In this example, the loop will run through all of the elements in this sequence before stopping once it reaches the 76ers element, which will be the last element displayed in the output.
Now let’s try a for loop with a continue statement:
teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”, “Nets”, “Hawks”]
for y in teams:
if (y == “Jazz”):
continue
print(y)
And here’s the output:
Heat
Cavaliers
Timberwolves
76ers
Nets
Hawks
In this program, the loop will run through MOST of the elements, but Jazz will be skipped, since that’s where the loop will continue.
- One thing I wanted to mention is that, with both
forandwhileloops, if you have abreakstatement in the loop, put theprintbefore thebreakstatement. However, if you have acontinuestatement, put theprintafter thecontinuestatement.
Now, I did mention that even though Python for loops aren’t capable of doing much in the way of calculations, they are capable of running through basic number sequences. Here’s an example:
for y in range(11):
print(y)
And here’s the output:
0
1
2
3
4
5
6
7
8
9
10
In this program, the range(11) function will print out 11 numbers. You might be thinking “What 11 numbers?”. You might be thinking the numbers 1-11 will be printed, but that is a common misconception. Whenever the range(N) function is used, the first number printed will always be 0, with each successive number being incremented by 1, until N-1 is reached, which is 10 in this case.
However, range() sequences don’t always have to begin with 0. Here’s an example of that:
for y in range(4, 13):
print(y)
And here’s the output:
4
5
6
7
8
9
10
11
12
In this example, range() has the parameters 4, 13. The program then prints out numbers between 4 and 13, but not including 13 (I’m not totally sure why 4 was printed but 13 wasn’t, but I guess it’s one of those weird coding rules).
Another thing about the range() function is that, even though it defaults to an increment by 1 pattern, you can change the increment pattern simply by adding a third parameter. Here’s how:
for y in range(20, 100, 14):
print(y)
And here’s the output:
20
34
48
62
76
90
In this program, range() has the parameters 20, 100, 14. The program will print out numbers between 20 and 100 using an increment by 14 pattern. The loop will stop running when it has reached the closet possible number to 100 (using the increment pattern).
You can also use decrement patterns in your for loops. Here’s how:
for y in range(112, 16, -8):
print(y)
And here’s the output:
112
104
96
88
80
72
64
56
48
40
32
24
In this program, the parameters for range() are 112, 16, -8. The program will start by printing 112; each subsequent number will be decreased by 8 until the closest possible number to 16 (using this pattern) is obtained. If 16 can be reached with this pattern (which it can), it will not be printed.
- With increments, make sure your second number is greater than your first. On the other hand, with decrements, make sure your first number is greater than your second.
- Also, remember to make the third parameter negative to denote a decrement pattern.
Now, let me show you what the else statement can do in a for loop:
for y in range(112, 16, -8):
print(y)
else:
print(“All done”)
And here’s the output:
112
104
96
88
80
72
64
56
48
40
32
24
All done
The else statement in a for loop is simple to understand, as it tells the loop what to do (or what to print) when it finishes iterating. In this case, the program prints out the same thing as the previous example along with the message All done when the loop is finished iterating.
Last but not least, I want to demonstrate and discuss the concept of a nested for loop. Here’s an example:
adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”, “hamster”]
for x in adj:
for y in animal:
print(x, y)
And here’s the output:
young dog
young cat
young ferret
young hamster
old dog
old cat
old ferret
old hamster
hairy dog
hairy cat
hairy ferret
hairy hamster
playfu] dog
playfu] cat
playfu] ferret
playfu] hamster
In this example, the program will print out one element from adj (or x) and one element from animal (or y). Since x is the first parameter of print adj (or adjective) will print first followed by y (or animal). In other words, the adjective describing the animal will be printed first, followed by the name of the animal. Since this is a loop, every animal’s name will appear once alongside every adjective.
But what if there weren’t the same amount of elements in each sequence? Here’s an example of that case (it’s the same program with the word hamster omitted):
adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)
And here’s the output:
adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)
So, even though I omitted a word, essentially nothing changes (well, aside from the omitted word). Each animal’s name still appears once alongside every adjective.
- For the record, you can’t create nested
whileloops.
Thanks for reading,
Michael
