Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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!") else: password = input("Sorry! The password you entered is incorrect. Please try again: ")
Thanks in advance for your help!
Steven Parker210,472 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.