Skip to main content

while-loops

A while loop is used to iterate over a given sequence like a list, string, or repeat a specific block of code. This is the catch though; we do not know upfront how many times we want to keep looping! We keep on executing as long as the condition in our while loop is true.

While

Example

i = 0

# print i as long as i is less than 5
while i < 5:
print(i)
i += 1

Infinite Loops

You might be feeling pretty confident right now with while loops... "It's easy! I just keep going as long my looping condition is true." Yes you are right about that but what would happen if your condition always stayed true? This is where we run into the infinite loop

When using a while loop, we want to make sure we have a condition that will eventually evaluate to false so we can exit our while loop. However if we do not do this, our program will be stuck in that loop until you close your program or your program consumes all available processor time before being booted out.

Bad Example

i = 0

# print i as long as i is greater than -1
while i > -1:
print(i)
i += 1