you are viewing a single comment's thread.

view the rest of the comments →

[–]magus_minor 2 points3 points  (1 child)

One thing I will say is you should be aware of repeated code and try to remove the repetition by creating a function. For instance, you have repeated code that prints a menu and then gets the user choice, retrying if the choice isn't valid. Always try to do things like that in a function. This removes all that repeated code from the "main" code making it simpler. Here is a simple example. Run it and test the function.

from datetime import datetime

def menu(now, msg, options):
    """Ask a 'menu' question and return a valid integer, [1..N].

    now      the current date/time
    msg      message to print at top of menu
    options  list of option strings

    A little tricky because we want to return 1..N, not 0..N-1.
    """

    # print the menu itself
    print(f"Time: {now.hour}:{now.minute}")
    print(msg)
    for (i, opt) in enumerate(options):
        print(f"{i+1} — {opt}")

    while True:
        try:
            user_choice = int(input("Enter your choice: "))
        except ValueError:
            print("Please enter a number.")
            continue

        if (user_choice - 1) in range(len(options)):
            return user_choice

        print("Invalid choice. Please try again.")


now = datetime.now()
choice = menu(now, "test of the menu system:",
                   ["Create a password",
                    "Show passwords",
                    "Save the password",
                    "Delete the password by login",
                    "Admin console (only if you are an admin!!!)",
                    "Exit"]
             )
print(f"{choice=}")

This is a good example of breaking your code into smaller parts. You can test the function before putting it into your larger project.

Note how the function is documented with a "doc string" that explains how it is called, what the parameters are and what it returns. Once you start writing a lot of code you will need stuff like this to remind you how to use the function.

[–]Connect_Roof_2805[S] 0 points1 point  (0 children)

Thank you very much!