Python Python Basics Functions and Looping While Loops

Miguel Richardson
Miguel Richardson
3,336 Points

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

3 Answers

Steven Parker
Steven Parker
203,211 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.

Miguel Richardson
Miguel Richardson
3,336 Points

Thank you for the information.

Stephen Thomas
Stephen Thomas
1,195 Points

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 ">="