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.
4 attempts; sys module does not seems to be working
note: I'm running this program on my local IDE
import sys MASTER_PASSWORD = 'opensesame' password = input("Please enter the super secret password: ") attempt_count = 1 while password != MASTER_PASSWORD: if attempt_count > 3: sys.exit("Too many invalid password attempts") password = input("Invalid password, try again: ") attempt_count += 1 print("Welcome to secret town")
After running this program, I input four wrong attempts. "Too many invalid password attempts" does not appears after the third attempt like in the video. I'm curious to see if anyone can figure out why this is happening.
Here is what appears in the shell:
Please enter the super secret password: hello Invalid password, try again: open Invalid password, try again: pleaseopen Invalid password, try again: ihopethisopens
Steven Parker210,469 Points
The argument to "sys.exit" is a status value, which is not used unless the exception it raises is intercepted.
If you want a message to be seen, do a "print" before performing the exit.
The video actually allows 4 attempts -- look at 6:37. The code there is wrong.
This is because the loop only triggers the exit comment when attempt_count is GREATER (>) than 3, ie, 4 or over. So it's the instructor who is wrong, not you.
You can fix it by simply changing ">" to ">="
Thank you for the information.
I actually solved this by reversing the count. Instead of counting up, my code counts down from three. Seemed to make more sense to me: I was looking at the attempts as "tokens" the user has to "spend" on tries to enter, and if the token isn't the right size, they don't get access.
import sys ## Asks for user to input their password. password = input("Please enter the super secret passsword: ") ## Sets the base number of password attempts. attempt_count = 3 ## Check to ensure password matches and display number of attempts remaining. while password != 'opensesame': if attempt_count == 0: sys.exit("Too many invalid attempts. Initiating self-destruct sequence.") if attempt_count > 1: password = input("Invalid password. " + str(attempt_count) + " attempts remaining. Try again: ") else: password = input("Invalid password. " + str(attempt_count) + " attempt remaining. Try again: ") attempt_count -= 1 print("Welcome to Secret Town!")