View Single Post
Old 2020-01-10, 01:53   #16
Dylan14
 
Dylan14's Avatar
 
"Dylan"
Mar 2017

32×5×13 Posts
Default While loops

In the last two sections, we covered for loops, which allows us to run a loop for a certain number of times. But say we want to run a piece of code if some condition is true. To do this, we can use a construct called the while loop.

The while loop:

The syntax of the while loop is as follows:
Code:
while [a condition is true]:
     do something
The condition must be a boolean statement, or it can be the elements True or False. If a boolean statement is given, then the program will evaluate the boolean statement and only evaluate the body of the loop if it evaluates True. If the element True is encountered, then the code block will continue forever (*). If the element False is encountered, then the code will not execute, as False is never True.
A simple example:
Let's sum the first ten positive integers. We can do this in a while loop:
Code:
sum = 0
i = 1
while i<=10:
  sum = sum + i
  i += 1
print(sum)
So, we first initialize a variable sum to 0 and i to 1. While i is less then or equal to 10, we add i to sum, and increment sum. Internally, sum goes as follows: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55. Once we ran through the loop 10 times, i is 11. But 11 > 10, so we skip the loop, and then print the sum, which is 55.

Infinite loops:

An infinite loop occurs in a while loop only, since as we recall, for loops only run until the iterable object is exhausted. We can create an infinite loop by creating a condition that cannot ever be false, for example:

Code:
while(True):
     do something
Of course, you should be careful with what you put into such a loop, as you don't want to end up running out of memory because you are trying to enumerate all the primes in a loop (**). There is a couple of things that this construct would be useful:
1. You are trying to monitor something on your computer, like CPU usage or GPU usage (***).
2. You are running a server and you want the server to run continuously so that clients can attach to it, communicate, and then detach at will.
3. You are running a DC project which can be left running for long periods of time.

Now, of course we can use break and continue to control while loops, which can be useful in infinite loops(****).
Example - Pascal's triangle
Pascal's triangle is a triangular array of the binomial coefficients, which are defined as follows:

{n\choose k} = \frac{n!}{k!(n-k)!}

Using while loops, we can compute the rows forever, however, using break, we will terminate after row 5 (*****):
Code:
i = 0
while(True):
  print("Row " + str(i+1))
  for j in range(i+1):
    entry = int((factorial(i))/(factorial(j)*factorial(i-j)))
    print(str(entry))
  i += 1
  if i > 4:
     break
This yields each of the first 5 rows of Pascal's triangle. Of course, we can change the number of rows that we print out by changing the number in the second to last line in the above code snippet (6).
Alternatively, if we want to do the same thing without break, this works:
Code:
i = 0
while(i <= 4):
  print("Row " + str(i+1))
  for j in range(i+1):
    entry = int((factorial(i))/(factorial(j)*factorial(i-j)))
    print(str(entry))
  i += 1
What about do... while loops?

When I mentioned loops in the first part of the for loop discussion, we mentioned that there is a thing called do while loops, where you do something at least once, and then you repeat if the truth value of the statement is true. Now Python does not have this construct (in stark contrast to C, C++, and Java), but you could emulate this. Here's a possible way to do this:
Code:
i = 5
while(True):
     #do something
     i -= 1
     if i == 0:
          break
Basically, we run something (the do statement), and then we decrement i, and then we run again (the "while" statement is true) until i = 0, and then we stop (the "while" statement is false).

(*) Well, forever in the sense that the code will continue to run until either one of the following happens:
1. There is an error that is encountered, which automatically stops execution,
2. Ctrl+C is pressed, which is the keyboard interrupt,
3. Some other thing happens which causes the code to stop executing (Windows update, BSOD, kernel panic, power outage, time limit exceeded in a Colab/Kaggle session, etc.).
(**) I wish you good luck if you want to do that.
(***) This is possible, see for example the gpustat package on PyPi.
(****) There are other things that we can use; for example, the command sys.exit(). We will cover the sys module later.
(*****) You will need to use the factorial function that I created, either in Part 1 of for loops, or in the section on functions.
(6) Just don't delete the last 2 lines, otherwise, you will not stop.

Last fiddled with by Dylan14 on 2020-01-12 at 00:20 Reason: add another method to compute Pascal's triangle. Same computationally, no break.
Dylan14 is offline