Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping While Loops

While Loops vs. If-Else

Hi! Just getting started here on Treehouse and this is my first post in the forums, so I apologize if this is formatted incorrectly.

I just learned about While Loops and although I think I understand the general concept, I'm not sure I understand why you would use a while loop instead of just an if-else setup.

For example, what makes the following pieces of code any different? The first is essentially the password checker code Craig writes in the while loops video, the second is a similar program using if and else instead. Is one any better than the other? They seem to produce the same exact result. Really, I'm just curious about what situations would require while loops rather than an if-else combination.

# While Loop version
password = input("Please enter your password: ")
while password != "password":
    password = input("Sorry! The password you entered is incorrect. Please try again: ")
print("Sign in successful!")

# If-else version
password = input("Please enter your password: ")
if password == "password":
    print("Sign in successful!")
    password = input("Sorry! The password you entered is incorrect. Please try again: ")

Thanks in advance for your help!

1 Answer

Steven Parker
Steven Parker
229,005 Points

The first version keeps giving the user another chance until they get the word right, and does not move on until they do. This would be an effective way to prevent someone who does not know the password from using the other parts of the program.

The second version checks the word only once, and while it gives a second chance for a wrong answer, it moves on without checking it again. So two wrong answers will get you to the same place as one right one. This would not be effective as a security measure.

I hadn't even considered that; I only thought to test the second version with one wrong answer. That makes a lot of sense. Thank you!