Friday 25 September 2020

Part Two: Lesson Four: The while Loop

As we discussed with the for loops, computers are very good at doing repetitive tasks over and over again and doing that very quickly using iterations. The while loop can also be utilized to achieve this.

The while loop iteration method is used to perform iterations as long as a condition exists except another condition causes a break in the loop such as finding a solution or exhausting all items to loop over. It is therefore possible to have an infinite loop.

          count = 0

          while count  < 10:

                   print(count)

                   count = count + 1

          print(‘All done’)

In the code above, we initialised our count to start at 0. Then set the condition that while count is less than 10, Python should print the value of count. Then increment the value of count by 1 and run the loop again as long as count is less than 10.

Notice here the colon after the while statement and the indentation below it to ensure Python knows that the lines belong to the while loop.

A more compact way to increment the count is as follows:

          count += 1

Hence, the code now becomes

          count = 0

          while count  < 10:

                   print(count)

                   count +=  1

          print(‘All done’)

 

The iteration in the code above would run as long as the while condition evaluates to True that is it would loop continuously until count is no more less than 10.

An infinite loop may occur if the conditions do not include an endpoint. For example, in the code above if we do not have the line to increment count by 1 in each loop, then count would remain 0 perpetually and would be less than 10 indefinitely and the while loop would go on forever until the program is stopped manually.

count = 0

          while count  < 10:

                   print(count)

                  

          print(‘All done’)

The code above would result in an infinite loop.

We would put all we have learned up to this point to build some programmes next.

 

No comments:

Post a Comment