Loops are extremely helpful when you want to perform a series of commands multiple times. Say you want your program to count to 100. You could start with a variable that equals 1, then print its value, then add 1 to it, then print it, and do this all the way up until the variable equals 100, but this would take 200 lines of code, and would be cumbersome to both read and write. With a loop, this same task could be accomplished in two lines of code. At the end of this tutorial, you will be able to do just that.
The first type of loop we will tackle is the while loop. This loop is essentially an if statement that is executed over and over, until its condition is false. Let’s analyze this example:
x = 0
while x < 15:
x = x + 1
x = x * 2
print(x)
print('Loop has ended')
>>2
6
14
30
Loop has ended
The first important aspect of the while loop is its condition, which in this case is x < 15. This essentially says, as long as x is less than 15 at the time that this statement is evaluated, the following block of code will be executed. In many ways, this is an if statement. However, what differentiates a while loop from an if statement is that when we reach the end of the code block, in this case, the line "print(x)", instead of moving to the next line of code below, Python goes back up to the top of the while loop, and checks the condition again. If the condition is still true, then the code block will be executed again, if the condition is false, then the block will be skipped, and Python will continue to execute the rest of the program following the loop. In this case, Python will jump to "print('Loop has ended')", once while x < 15 becomes false.
Observing the output of the previous example, after the loop’s first iteration, x’s value is 2. 2 < 15, so the loop is executed again, and x’s value is 6. After the third iteration, it is 14, and finally after the fourth iteration, 30. 30 is greater than 15, so the while loop’s condition is false, and the code block is not executed again.
If we want further control on specifically when, inside the code block of a loop, we want the execution to end, we can use break and continue statements. A break statement will terminate the loop, whenever it is reached, and can be used for checking certain conditions which we would like to end the loop. Here is an example:
x = 0
y = 0
while x < 100:
x = x + 1
x = x * 2
y = x % 5
print('x:', x, 'y:', y)
if y == 0:
print('x is a multiple of 5, end the loop')
break
>>x: 2 y: 2
x: 6 y: 1
x: 14 y: 4
x: 30 y: 0
x is a multiple of 5, end the loop
The use of break statements can add flexibility and readability to your loops, and they can be a powerful tool.
A continue statement is similar to a break statement, but instead of breaking completely out of the loop, it tells Python to immediately go back up to the condition line. This can be useful if, when a certain condition is met, we do not want to execute any of the code below the continue statement, but we don’t want to use a break statement because we want the loop to continue. Here is an example:
x = 20
y = 10
while x > 0:
x = x - 5
print('x:', x)
if y <= 0:
print('y is already 0')
continue
y = y - 5
print('y:', y)
>>x: 15
y: 5
x: 10
y: 0
x: 5
y is already 0
x: 0
y is already 0
You might have noticed that the above continue statement could easily be replaced by making the code below it into an ‘else’ branch of the if statement above it. This is true in many cases, but using continue can improve the readability of your code and in some niche cases can be more helpful than an if-else branch, so it is a useful tool to be aware of, even if you might not use it too often.
One last note about while loops is that the variable used in the condition of a while loop must be updated at some point within the while loop. If this never happens, the while loop will continue to execute forever until you manually stop the execution of your program, which can be harmful to your computer or simply not make your code work as intended.
The second kind of loop is the for loop. While the while loop will continue until a specified condition is not met, the for loop will continue until it has looped a certain amount of times. For loops are preferred when we know exactly how many iterations of the loop should execute, or if we are looping through a data structure, such as an array.
Python for loops are more flexible than the for loops of other languages. The first use for a for loop in Python is to iterate a certain number of times. Say we want to call a function ten times, we would use a for loop in conjunction with the range() function, like this:
for i in range(10):
print(i)
>>0
1
2
3
4
5
6
7
8
9
This specific syntax is helpful when we know the number of times we want the for loop to execute, probably the most common use for the for loop. Notice the variable i, which does not have to be initialized beforehand, which keeps track of the number of iterations the for loop has completed. Note that i does not start at 1, but rather at 0, and it does not end at 3, but rather at 2. In computer science, most of our counting starts at 0 and ends at n-1. There are still the same amount of iterations, but this method of counting makes things like indexing a list much easier.
Here is the exact same code as above, but if we used a while loop instead:
i = 0
while i < 10:
print(i)
i = i + 1
>>0
1
2
3
4
5
6
7
8
9
Hopefully this shows how the while and for loops are two sides of the same coin, but each has its own domain in which it is preferred.
A great tool of the for loop in Python is that it can easily iterate over the contents of a list. We will go over this concept more in depth when we get to lists, but here is a taste of why the for loop is powerful in these scenarios:
fruits = ["apple", "orange", "pear"]
for fruit in fruits:
print(fruit)
>>apple
orange
pear
Notice how I did not use the variable "i" in this case, in favor of "fruit", for my iteration variable. This is because that variable can be named whatever you want. We typically use "i", or some other letter, for when the iteration variable is an index, and a more descriptive variable for cases like this, when the iteration variable is some object that has context.
Similar to if-else branches, both while and for loops can be nested. We can have any kind of loop inside any other loop. This can be very useful when we want to iterate over lists which have more than one dimension, a concept we will talk about at length later.
for i in range(3):
for j in range(3):
print(i, j)
>>0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Notice that we use a different iteration variable in the two loops. If we used i as the variable for the second loop, we would not get the same results, as the variable would be reassigned constantly. Using two for loops with the same number of iterations, we were able to produce each combination of two integers, whose values are between 0 and 2, a handy mathematical tool.
I hope this tutorial helped you understand the value of loops. With just if-else branches and loops, you could code anything, but it would not necessarily be easy. From here on out, we will be learning about tools which can make our jobs even easier. First up are functions.
Challenge Activities:
Write a program that prints all numbers from 0 to 10, except 3 and 8.
Write a program that prints numbers from 0 to 50. If the number is a multiple of 3, have it print "Fizz" instead. If it is a multiple of 5, print "Buzz". If it is a multiple of both 3 and 5, have it print "FizzBuzz".
コメント