When you are unsure how much data your application may need to process it is probably appropriate to use a while statements. The while statement we keep processing until it runs out of items to process. If you remember with a traditional for loop the limit is preset by the data structure you are analyzing.
Since they can go on forever it is possible with a while statement to create an endless loop. This is a loop that never stops processing. This will essentially crash most computers and should naturally be avoided. To avoid this you need set the environment, state the while statement, and update the condition of the environment. Below is a simple example of this.
- In line 1, we have the environment for the condition which is a variable called “number” set to 0.
- Line 2 is the while statement which states that as long as “number” is less than 10 do the following.
- In line 3 the variable “number” is printed.
- In line 4, after “number” is printed the number 2 is added to the current value
- This takes place until the variable “number” is equal to ten.
Below is what the output looks like if you ran this
You can see that we start with 0. This is because we set the variable “number” originally to 0. Then the value increases by just as in line 4 of the code above.
Nested for Loops
Just as with functions you can also have nested for loops. This is a loop within a loop. Below is a simple example.
- Lines 1-2 as for input and you can type whatever you want
- Line 3-4 is the first for loop at it process whatever your input is from line 1. The final result is that the loop prints this
- Line 5-6 are the second for loop and simply processes whatever you inputted in line 2. This loop simply prints the input from line 2.
Here is what the output would look like
You can see that the loops took turns. The first loop ran its first letter them then the second loop ran everything. Then the first loop ran its second letter and the second loop ran everything again. Therefore, nested for loops affects the timing of when the code is ran.
This post looked at the use of while statements and for loops. while statements are useful when you do not know how long you may need to process data. for loops allow you to run complex looping in which you are trying to do multiple tasks.