While loops now. You already learnt about for loops and we were able to execute
the print statement multiple times using a for loop. For loops are used much more
often than while loops, but while loops also have their area of application
sometimes and in this lecture I'll write a very very small program that will
demonstrate the syntax of a while loop so let's start. A while loop starts with
the while keyword. Let's say we want to write a program that will compare a
password against the value that the user enters
and while the password entered by the user is not the same with a
password that we know, the loop will keep occurring over and over again until the
user enters the real, the correct password. So while the password is different from
let's say the real password is by Python123 and we need a column there and
notice that these two symbols mean is not and here we are comparing a variable
to a value, but we don't have a variable yet declared, so first we need to declare
the variable here. The password equals to an empty string so that's the initial
value before the user enters their own value and here we want to get the
user value, and here we want to store the value entered by the user in our
password variable. So input enter password. Now once we get the value in
our password variable, we want to compare that variable and we compare it against the
real password, so python123, so if the value entered by the user is equal to
Python123 we want to print out the string you are logged in, else so if this
evaluates to false we would have another action here.
That would be, sorry try again. That's it. Let's test this now
before I go over the code again and explain things better to you, so save.
Then go to your command line. That's the script number 6, so let's try our own password here.
Let's say just python. Sorry try again. Try again. Python 1. No. Python123.
And you are logged in. So we are just printing out some lines here some text,
but in a real-life situation we would be expecting a real user log ins.
We would have to write some longer code here that basically would show the user
the internal pages of your website, of your web application, so you would unlock
your user content of your website. So again what we have here? While password
is not equal to one two three this block of code will be executed over and over again.
Once the value gets equal to Python123, the loop stops
running and so does the script, so I believe this is a very nice explanation
and example for you to understand the while loop. Again you'll be using the for
loop much more than the while loop but this is good to know and it was also a
good practice for you I believe. See you in the next lecture.