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

Marlon Glover
Marlon Glover
622 Points

Why input a new variable in the While loop?

Why do we ask for a new assignment of the variable 'password' within the While loop instead of using print("Invalid password, try again: "? I definitely missed this in an earlier video, and now it's bothering me.

while password != MASTER_PASSWORD: if attempt_count > 3: sys.exit("Too many invalid password attempts") password = input("Invalid password, try again: ")

2 Answers

Megan Amendola
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree seal-36
Megan Amendola
Treehouse Teacher

I'm assuming the code should look like this:

while password != MASTER_PASSWORD: 
    if attempt_count > 3: 
        sys.exit("Too many invalid password attempts") 
    password = input("Invalid password, try again: ")

Remember while loops continue to loop unless password != MASTER_PASSWORD becomes False or the loop is broken in another way (the sys.exit(), a return statement, etc.). Inside of this loop, you are checking how many time someone has attempted to input a correct password. If the number of attempts is greater than 3, then the app exits. You also ask the user to input their password, if it is correct then password != MASTER_PASSWORD becomes Falseand the loop is terminated. If the user inputs an incorrect password, then password != MASTER_PASSWORD is still true and the user is asked for their password again because it was invalid. This continues until the user either uses up all their attempts or inputs the correct answer.

So long story short, the password input is inside the loop so the user has chances to continue to input their password until they get it right (or run out of attempts).

Hope this helps!

Marlon Glover
Marlon Glover
622 Points

Yes! This is very helpful. Thank you for the detailed explanation.