I am new to python and I am trying to write a program, when every time a user inputs a incorrect/failed password attempt it will write it into a file. Which records the time/date and the reason why its invalid. Then should display the output.
I've tried running my code but it always comes up with an error:
log_file.write({todays_date},{reason_password_invalid}) UnboundLocalError: local variable 'todays_date' referenced before assignment
I am not sure why that it. Is my code not correctly written to be able write into a file every time it is incorrect?
import datetime
def main():
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
PASSWORD_LOG_FILE = "password_log.txt"
password = input("Enter your password: ")
password_length = len(password)
if password_length > MIN_PASSWORD_LENGTH and password_length < MAX_PASSWORD_LENGTH:
if password.isalpha():
message = "Your password is weak! It only contains letters."
elif password.isnumeric():
message = "Your password is weak! It only contains numbers."
else:
message = "Your password is strong! It contains letters and numbers."
else:
my_date = datetime.datetime.today()
todays_date = my_date.strftime("%A%B%d%Y")
if password_length < MIN_PASSWORD_LENGTH:
reason_password_invalid = "password_length < 6"
else:
reason_password_invalid = "password_length > 14"
log_file = open(PASSWORD_LOG_FILE, "a")
log_file.write({todays_date},{reason_password_invalid})
log_file.close()
log_file = open(PASSWORD_LOG_FILE, "r")
for line in log:
print(line, end="")
log_file.close()
main()
The todays_date
and reason_password_invalid
variables are only defined in the else
block of your main if
statement, so you would get the said exception if the user enters a valid password.
You should write to the log file only if the user enters an invalid password instead:
else:
my_date = datetime.datetime.today()
todays_date = my_date.strftime("%A%B%d%Y")
if password_length < MIN_PASSWORD_LENGTH:
reason_password_invalid = "password_length < 6"
else:
reason_password_invalid = "password_length > 14"
log_file = open(PASSWORD_LOG_FILE, "a")
log_file.write(f'{todays_date},{reason_password_invalid}\n')
log_file.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.