# Mini Lesson 5: While Loops

While loops is similiar to for loops, however there are a couple of key differences. The first is how while loops are told how long to iteratare for. With for loops, we would either simply iterature through an entire list or determine how many indexes to interatre through using the range() function. With while loops it is much more simple, as you can say to continue looping until a value is greater than a set value. Here's an example of a while loop:

x = 1

while x < 10:

print('Hello World %d' % x)

x += 1

This would output Hello World with an increasing number, which is increasing due to our += at the end of every loop. The loop would continue printing out Hello World until x being less than 10 was false, which would be 9, because once the loop checked if x, which would be 10, was greater than 10, it knows that is False and would break the loop.

Another interesting option for while loops would be to use the break statement. Just for a refresher, if our code ever reaches a break statement, such as through an if statement, the while loop would stop iterating. Here's an example using a break statement that would replicate the same thing as the past code:

x = 1

while True:

if x == 10:

break

else:

print('Hello World %d' % x)

x += 1

With the while True, if we didn't set the if statement with the break, the loop would continue forever, and we would have to press the red square at the bottom left of the screen to make the code stop. With the if statement, we say if the x, which increases by one everytime it iterates, is equal to ten then we break the loop, and Hello World isn't outputted with a 10.