Python - While Loops

While Loops

From the official Python website:

A while-loop will keep executing the code block immediately below and in the current block until a condition is True.

We need to remember, a colon (:) instructs Python to start a new block of code. The next line is indented by 2 spaces, officially from the PEP8, however, I tend to prefer 4 space indentations for better readability.

I'm sure there are many people who would disagree with that statement. It's just a personal preference.

You must structure your programs in order for Python to know how to interpret your code's meaning.

While-loops essentially test an if-statement, but instead of running the code block once, the while loop jumps back to the top of the code block where the while is located, and repeats until a condition is met.

One major problem with while-loops. They do not always stop. You should always add break statements inside of while loops to prevent this from happening.

To avoid these problems, there are some very important rules you should follow closely:

i = 10  
numbers = []

while i < 26:  
  print("At the top i is %d" % i)
  numbers.append(i)

  i = i + 1
  print("Numbers now: ", numbers)
  print("The bottom integer is %d" % i)
  break
else:  
print("The numbers: ")

for num in numbers:  
    print(num)

Craig Derington

Veteran full stack web dev focused on deploying high-performance, modern applications using Python, Go and Node; featuring industry leading frameworks, Django & Flask, and backends MySQL and MongoDB.

comments powered by Disqus