Loops are a kind of control flow, but they rerun the same block of code over and over again until something else tells the loop to stop repeating itself. This is a bit different from conditional statements since these only run the block of code once. The two kinds of loop are while
and for
. Both types of loop are really useful.
while is one kind of loop. When we make a while
loop, the program repeats itself until a given block of code happens. When programming a while
loop, we need to create some rules, or our program will run forever.
For example, we can make this rule: when the calculator is on, perform the following steps:
Run the calculator.
Prompt the user to keep calculating.
When the user hits the
else
statement, turn the calculator off.
Let's go through each of the code changes step by step; you will need these changes in order to make the while
loop work.