Monday, June 10, 2019

The While Loop in Python

In order to perform operations over and over again in a programming language you need to have syntax that allows you to execute the same lines of code without having to re-write each individual line. In python there are a few ways to do this and one way is the while command.

The indentation is important in python. All statements under the while command must be indented by at least one space, and by convention some programmers use 4 spaces. If you use an editor the tab key must be setup in the editor so that when you press tab it really insert spaces instead of tabs.


The below example will print Hello n until the end of time or you press CTRL-C.

i = 0
while True:
 i += 1
 print("Hello "+ str(i))


This is what we refer to as an infinite loop and when I learned programming 20 years ago we were told to avoid them at all cost because it would hang your computer and cause you to lose your work. But python, and modern operating systems for that matter, are very good and handling this situation.

The output for the above program is as follows:


Hello 2548067
Hello 2548068
Hello 2548069
Hello 2548070
Hello 2548071
Hello 2548072
Hello 2548073
Hello 2548074
Hello 2548075
Hello 2548076
Hello 2548077
Hello 2548078
^CHello 2548079
Hello 2548080
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt

You will notice ˆC and the KeyboardInterrupt in the output. This is expected behavior because we never gave a command to end the loop.

Also understand that inside of the parenthesis we used "Hello " + str(i). This is called string concatenation. We use the plus operator, which you would expect to be used for math operations, to join two strings together. The str(i) function is used to convert i, which is an integer, to a string instead.

For a dynamic language python can be strict on using types. Many dynamic languages would automatically assume that you wanted i to be converted to a string. Python simply wants to make sure that you really intended on converting i to a string before it joins it to "Hello".


https://www.w3schools.com/python/python_while_loops.asp - More information about while loops and for loops.

I am writing this blog and testing my examples using an iMac very similar to this one. You don't really need a powerful computer but its nice to have one that has a nice display and is very quite. Macintoshes are very elegant and the unix base that OS X is built on helps me to access unix command line tools which I find more powerful than Windows command prompts.




No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...