Python Forum

Full Version: Help with my code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have been working on my code but I am a novice and I am still trying to get my head around it all. I can't get the output I am looking for. Everything I have tried doesn't work and I am close to pulling my hair out lol! Any help would be much appreciated but I am not looking for others to do the work for me! Just need help getting to the answer. Thank you.

The assignment is:
"For every incorrect password length, the program will record an entry in a password log file that will include the date/time (updated to the nearest microsecond) and the reason why the password is invalid either “password < 6” or “password >10”. The file will not store any passwords. Once the length is valid, the program will output the length of the password and determine if the password is weak or strong as in the previous version. The program will then output each line of the password log file to the screen."

Problem 1.
I now have the output with the date, time and the reason why on one line e.g. 2023-09-07 18:55:45.427403 password > 10.
I want to put a comma after the time and before the word password e.g. 2023-09-07 18:55:45.427403, password > 10. I have tried many variations, but I get a squiggly line and/or the code doesn't work.

Problem 2.
I have followed the examples/exercises that we have been given but I don't think the input/output coding is correct. If it's not, I don't know what is incorrect! I have attached new screenshots of the outputs.

import datetime


def main():
    input_file = open("password_log.txt", "r")

    for line in input_file:
        print(line, end='')

    input_file.close()



# INPUT
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 10
output_file = "password_log.txt"
password = input("Enter your password. It must be a minimum of 6 and a maximum of 10 characters. ")
password_length = len(password)
# OUTPUT
if len(password) < 6:
    print(f"Your password has {len(password)} characters and is too short.")
    print(datetime.datetime.today(), "password < 6")
    new_password = input("\nEnter your password again. ")
    output_file = open("password_log", "a")
    output_file.write(new_password)
    output_file.write("\n")
    output_file.close()
if len(password) > 10:
    print(f"Your password has {len(password)} characters and is too long.")
    print(datetime.datetime.today(), "password > 10")
    new_password = input("\nEnter your password again. ")
    output_file = open("password_log", "a")
    output_file.write(password)
    output_file.write("\n")
    output_file.close()
if password.isalpha():
    print(f"Your password has {len(password)} characters and is weak. It only contains letters.")
    print(datetime.datetime.today())
elif password.isnumeric():
    print(f"Your password has {len(password)} characters and is weak. It only contains numbers.")
    print(datetime.datetime.today())
else:
    print(f"Your password has {len(password)} characters and is strong. It contains both letters and numbers.")
    print(datetime.datetime.today())
main()
# END
Make sure you are doing the assignment.

Assignment instruction:
For every incorrect password length, the program will record an entry in a password log file that will include the date/time (updated to the nearest microsecond)

From your post:
I can't work out how to get the output like this; 2023-09-07, password < 6

That date/time string does not have any time. Certainly not any time to the nearest microsecond.

I would start with a program like this:
from datetime import datetime

print(datetime.today())
Output:
2023-09-06 12:31:50.190394
That date/time string has time, and it is updated to the nearest microsecond.

Now try printing the date/time string and a message.
from datetime import datetime

print(datetime.today() "is the current time.")
Output:
2023-09-06 12:46:29.283713 is the current time.
That certainly was easy. I wonder if there is a way to print to a file? That might be worth looking into. Printing automatically appends a newline ("\n") and it has formatting. Looks like a better choice than write().

Quote:The log file has only kept 4 incorrect password attempts
Your program only writes 1 line to the password file. Should it process multiple passwords? To do that you would need a loop that got a password, checked the password, logged the entry.

Your program only writes to the log file if the password is too short or too long. If the password is weak you only print the message to standard output (the console). You are not writing to the log file.
(Sep-06-2023, 07:24 PM)deanhystad Wrote: [ -> ]Make sure you are doing the assignment.

Assignment instruction:
For every incorrect password length, the program will record an entry in a password log file that will include the date/time (updated to the nearest microsecond)

From your post:
I can't work out how to get the output like this; 2023-09-07, password < 6

That date/time string does not have any time. Certainly not any time to the nearest microsecond.

I would start with a program like this:
from datetime import datetime

print(datetime.today())
Output:
2023-09-06 12:31:50.190394
That date/time string has time, and it is updated to the nearest microsecond.

Now try printing the date/time string and a message.
from datetime import datetime

print(datetime.today() "is the current time.")
Output:
2023-09-06 12:46:29.283713 is the current time.
That certainly was easy. I wonder if there is a way to print to a file? That might be worth looking into. Printing automatically appends a newline ("\n") and it has formatting. Looks like a better choice than write().

Quote:The log file has only kept 4 incorrect password attempts
Your program only writes 1 line to the password file. Should it process multiple passwords? To do that you would need a loop that got a password, checked the password, logged the entry.

Your program only writes to the log file if the password is too short or too long. If the password is weak you only print the message to standard output (the console). You are not writing to the log file.

Hi, I have edited my OP.
If you look up the docs for datetime, you will find it allows you to format the output string in many ways. You can show all or just part of the info.

Open the log file 'a' to append to the existing file, but that will create the file if it is not there.

I think this will do something like what you want. Just some fun on Sunday morning!

from datetime import datetime
# in case you want to do time zone stuff
from zoneinfo import ZoneInfo

path2log = '/home/pedro/temp/password_log.txt'

def logit(password):    
    if len(password) < 6:
        reason = 'too short'
    elif len(password) > 10:
        reason = 'too long'
    elif password.isalpha() or password.isnumeric():
        reason = 'weak'
    else:
        reason = 'strong'
    # only log unacceptable passwords
    if not reason == 'strong':
        dt = datetime.now()
        date = dt.strftime('%A %d-%m-%Y, %H:%M:%S.%f')        
        with open(path2log, 'a') as mylog:            
            mylog.write(f'Password: {password} attempted on {date} declined because it is {reason}. \n')
        return False   
    else:
        print(f'{password} is a good {reason} password! You will be a secret agent someday!')
        return True
        
acceptable = False
while not acceptable:
    print('Please enter a password between 6 and 10 characters long.')
    print('Your password should contain at least 1 non-alphanumeric character.') 
    password = input('Enter your password. It must be a minimum of 6 and a maximum of 10 characters and have at least 1 non-alphanumeric character. \n')
    acceptable = logit(password) 
I am confused by your code. What do you think your program is supposed to do? Describe in your own words.
@deanhystad

Moi?

It should reject a password that is too, short, too long or too weak.

I thought that's what the OP wanted. Haven't tried it rigorously, but it seems to work.
Sorry Pedroski, not your program. I thought I might know what the code in the original post was meant to do, but later posts by bp12 have me confused. Is this program supposed to loop until a strong password is entered, or does it fail/pass, add a log entry and exit? Does the program run in a loop, letting you enter multiple passwords? Should the log file start fresh each time the program is run?
My original post is part 2 of the assignment which I have now completed.

Part 1 of the assignment is "a program is required to input a user password, calculate the length of the password and validate the length of the password to ensure it contains the minimum number of characters 6 and a maximum of 10 characters. Continue to input the password and calculate the length of the password until a valid length password has been entered.

Once the length is valid, the program will output the length of the password and determine if the password is weak or strong. If the password only contains letters output a message stating “password weak - only contains letters” or if the password only contains numbers output a message stating “password weak - only contains numbers” otherwise output a message stating the password is strong, that is, it contains a combination of letters/numbers or other characters."

I am currently working on part 3 of the assignment.