Let’s imagine that you’re the world known runner. You’re about to run 5 laps at the upcoming Olympics. Before running, you remind yourself that you need to run exactly 5 laps. No more, no less. Ready, Set, Go! You ran 1 lap. It’s not 5, so you keep running. Lap 2, 3, 4, 5 and you stop running. Well done!
Loops work exactly the same. First, you define a condition that tells a program when to stop. Second, you run code inside the loop. If the condition is met, then we’re done. Otherwise, we run code again.
Run it. You should see this output.
Let me explain what happened here. On the first line we declare the variable named lap with the value of 0. Next, we use the special keyword while following the condition.
While this condition is true, the code block located between the keywords while and end will be run.
Let’s evaluate the condition at the first time. The value of lap is zero. Zero is less than five. The condition is true. What do we need to do? Right! We need to run code inside the code block. We enter the code block. We output “keep running” and increase the variable lap by 1. At this point, we finished executing the inner code block and it’s time to check our exiting condition again. The value of the lap variable is one. One is less then five. The condition is true which means that we need to run the code again.
Rinse and repeat 4 more times. Now is the moment of truth. The value of lap is 5. We’re at the end of our code block. We evaluate our condition. Five is not less the five. The condition is false. Yay! We don’t need to execute the inner code block. We’re done.
until keyword acts in the opposite way of while.
Until this condition is true, the code block located between the keywords while and end will be run.
Here is the same example written using the until keyword. Notice that the condition now checks if lap variable is greater then 5.
Photo by roy.luck