So I'm working on a password program that logs all incorrect attempts (just the date and time with an error message saying why) The issue I'm having is when I input a password that is say, >10 and then input a password that is <6...all failed attempts will be logged as >10 even if that isn't the case.
I'm very much a beginner to Python so feel free to explain everything to me like I'm 5.
import datetime
def main():
MIN_LENGTH = 6
MAX_LENGTH = 10
PASSWORD_LOG_FILE = "password_log.txt"
password = input("Please enter your password for checking: ")
password_length = len(password)
while len(password) < 6 or len(password) > 10:
print("Invalid")
error_log = str(datetime.datetime.now())
output_file = open(PASSWORD_LOG_FILE, "a")
output_file.write(error_log)
password = input("Please enter your password for checking: ")
if password_length < MIN_LENGTH:
output_file.write("{}, password <6".format(error_log))
elif password_length > MAX_LENGTH:
output_file.write("{}, password >10".format(error_log))
output_file.write("\n")
output_file.close()
if password.isnumeric() is True:
comment = "password is weak - contains only numbers."
elif password.isalpha() is True:
comment = "password is weak - contains only letters."
else:
comment = "password is strong."
print("Your password is {:} characters long".format(len(password)))
print("Your {:s}".format(comment))
input_file = open(PASSWORD_LOG_FILE, "r")
for line in input_file:
print(line, end='')
input_file.close()
main()
I realise an issue may be in the "While" loop and tried moving bits of code around and re-formatting but I either trigger an endless loop or the error message doesn't begin in a new line etc. As mentioned above, What I would like to happen is that it tells me the password was invalid because it was either <6 or <10. Right now it logs all incorrect attempts as the same as the first attempt - I can't seem to locate the dodgy line of code that is causing this!
You store password_length
once at the start, and use it in your if
check. However, len(password)
is not the same as password_length
! You correctly use len(password)
in your while loop, but you don't update password_length
to the new length after you retype a password.
You have a few options of how to fix this, but I think the easiest one may be to add the line password_length = len(password)
just after password = input("Please enter your password for checking: ")
.