I WILL LOVE YOU WHILE [condition]:

--Originally published at Coding The Future

Image via GIPHY

I know. I've gotta stop with the song references. But today's topic reminds me of Whitney Houston's "Love You". That song is so beautiful, so inspiring, but it's all FALSE! Well, kind of... Why? Because nothing lasts forever. Well, maybe true love does. But in code, the chances you'll encounter a loop that never ends are super rare.

Today we'll be talking about while loops, which helps us run a piece of code while a certain condition is met.

For example, let's say we wanted to print a countdown. Instead of writing a single line for each number, we would just go to while loops!

While loops are super simple in Python. Begin with the keyword while and then write the condition –without brackets! The following lines, which are obviously indented, is where you put the code that'll loop. Take a look:

count = 0
while (count > 0): print ('The count is:' + count) count = count - 1

As you can see, the loop will run while count is grater than 0, and will stop running once count reaches 0. The count is decreased by 1

For your condition, you can use counters like the example above, or you could use a boolean value by nesting if-statements inside of your while loop. You've gotta be careful though, because as I said, you could get stuck into an infinite loop, which could break your program.

That's pretty much it for today. Until next time!
@emamex98