Project 13: Use of loops with ‘while’

--Originally published at TEC GDL 2016

In this blog post I will be covering the use of loops with the “while” statement. The only difference to a ‘for’ loop (for more information visit my last blog post) is, that the while loop statement executes a target statement when a given condition is true (not just when a lists content is exhausted).

If the condition this is based on turns out to return a False value, then it may happen that the function will not be executed at all or the function continues on using the ‘else’ statement you are able to attach to it.

For a general understanding of these loops have a look at the following flow diagram:

python_while_loop.jpg

The given syntax of a ‘while’ loop always looks like this:

   while expression:
               statement(s)
   else:
               statement(s)

In this example ‘statement(s)’ can be a single statement or a block of statements. Our condition can be any expression. The loop keeps iterating while the condition is true.

For a very simple use of the ‘while’ loop have a look at the following

Bildschirmfoto 2016-10-26 um 19.16.44.png

When you use ‘while’ loops with an ‘else’ statement, the else statement is executed as soon as the condition of the while loop is not met any further.
Have a look at the following code in order to understand this better:

bildschirmfoto-2016-10-26-um-19-42-22

The following output is shown once you execute this program:bildschirmfoto-2016-10-26-um-19-42-30

Thank you for visiting my blog once more and hope you learned something today?

For any questions hit me up on Twitter @tecjames or ask any question in the comment section!

Cheers,
James de Tec

Sources:

https://wiki.python.org/moin/WhileLoop
https://learnpythonthehardway.org/book/ex33.html
https://www.tutorialspoint.com/python/python_while_loop.htm