When to use while

hey guys - working through the cs 101 course and find i’m quick to use if or for loops but can never quite figure out when a while loop is the best option .

wondering if anyone has advice on how to spot a problem that is best solved using a while loop! thanks :slight_smile:

Hi there

In a lot of situations they’re interchangeable. But if you would work with user input, like a password, a while loop might work better.

A very crude example:

def password_test(password):
   pwd = input('password please')
   while pwd != password:
       pwd = input('please try again')
   print('you are now logged in')

Now if you would do that with a for loop you would probably need to save all entered passwords somewhere in a list or something, which would be very cumbersome.

You can try writing a for loop for each while loop you make and vice-versa, and quite quickly get the hang of which one to use in what situation.


@srmarshall2, I recommend recreating this code out and trying different passwords to the one you input. This is an excellent example and one of the ways I learned the benefit of using while loops instead of for loops!

1 Like

thanks! this was super helpful - sounds like thinking about if a while loop can help me avoid creating a potentially unnecessary variable would be a good way to fact check myself