Sometimes we need to repeat code in our programs for a certain number of executions. Let’s consider the classic triangle problem:
= == === ==== ===== ====== ======= ======== ========= ==========
This is a typical problem that computer science students use to learn about loops. In this problem, we have to print a triangle to the console where the size is specified by the user. Since we don’t know the size of the triangle ahead of time, we won’t be able to do something like this:
print('=') print('==') print('===') # continued...
Our issue is that right now, this code can only print a triangle that has a base size of three. If the user wants ten, we are out of luck. What we need is a programming construct that will continue to build the triangle until it hits the proper size.
Here is the example code of how to do this
size = int(input('Enter the size of the triangle => ')) counter = 0 while counter < size: # counter < size is the terminating condition. # The next two lines repeat as long as condition < size print('=' * counter) # Print the triangle counter += 1 # Important! Update the counter variable!
This code accomplishes what we want it to do. This is the output we get when we run this code.
Enter the size of the triangle => 5 = == === ====
Let’s talk about why this works. While loops begin with the
while keyword followed by a condition. The loop will repeat code inside of the while block as long as the condition is true.
In our case, the condition is
counter < size so as long as our counter is less than the size of the triangle that the user specified, our condition will be true and the loop will continue to repeat. As soon as
size >= counter the loop will terminate and the program will return to it’s normal execution flow.
Inside of the triangle, we print our triangle and then update our counter variable by 1. It is critical that we update our counter variable because without it, the loop will run forever.
while counter < size: print('=' * counter) print('Loop is over') # Note! We never get to this statement! How come?
The code above will run forever in what is called an 'infinate loop'. The reason this happens is that we fail to increment the counter variable. Remember that loops always run while the terminating condition is true. Since counter is always less than size, our condtion never becomes false and the loop runs forever.
Sometimes we make infinate loops on purpose
while True: print('Infinate loop')
Since we are passing the contant
True to our loop here, our loop will run forever. It’s on the developer at this point to kill the loop, which will learn when we cover the
Finally, Python let’s us add an else statement to while loops that will run once the loop is over.
size = int(input('Enter the size of the triangle => ')) counter = 0 while counter < size: print('=' * counter) counter += 1 else: print('triangle complete') # This code runs when the loop is over