Conditional Repetition: while Loops
00:00
Now let’s take a look at some situations where a programmer might use an or
statement within a while
loop.
00:07
They are similar conditions as when you’re using an if
statement: having a choice of values to enter or continue a loop or checking to see if an input value is outside of a range of specific values.
00:20 Sometimes, we use this to actually guarantee that an input value, for example, might be inside of a specified range of numbers. Let’s take a look.
00:33
So, here’s a sample program where the programmer wants to make sure that the user enters a number between 1
and 10
. And so we have the appropriate input statement and then we do a check. If the number is less than 1
or it’s greater than 10
, they haven’t entered an appropriate number and so we’ll give them a second chance.
00:54
But this assumes that the user is going to get it right the second time and not maybe make a mistake again. What’s even better is to replace the if
with a while
.
01:05
Now this while
loop will continue and the user will continue to be prompted for a number between 1
and 10
. And if that doesn’t happen, we go back to the beginning of the while
loop, the condition is True
, and repeat it until we eventually get an appropriate number that the program is expecting. Now, what if they never enter an appropriate number? Well, you can create a more complicated loop condition to let that happen, but that’s not the topic for this particular course. But there we can see an example of how to use an or
condition within a while
statement.
Become a Member to join the conversation.