Neosify - Buy, Stake & Earn Crypto
Neosify - Buy, Stake & Earn Crypto
Neosify - Buy, Stake & Earn Crypto

Python | Password Generator

By Casper_x | Python Programs | 2 Mar 2023


Password Generator

 

Secure your accounts with strong passwords using our fast and efficient Python script, which can generate unique passwords in just a few seconds.

 

          What is random library ?

 

The ‘random’ module is a Python library that provides functions for generating random numbers. These numbers can be used to simulate random events or create test data. The ‘random’ module offers several functions to generate different types of random numbers, such as integers, floating-point numbers, complex numbers, and random sequences.

The ‘random’ module also provides functions to shuffle sequences, choose random elements from sequences, and other useful operations for manipulating random data. Additionally, there are additional modules in Python, such as ‘secrets’, that provide functions for generating more secure random numbers, such as encryption keys.

(Let me know in comment if you want a post about secret module)

In summary, the ‘random’ module of Python is a useful tool for developers who want to create programs that require random or pseudo-random elements.

 

          Program :

 

This Python code generates a random password of the length specified by the user, with special characters, uppercase and lowercase letters. It also offers the option to save the password to a text file.

To build this code, you need to create 3 functions with the following steps  : ( I tried to simplify as much as possible )

1. Import the random module to generate random choices.

import random

2. Define the 'p_generator()' function to generate the password. This function contains the following steps:

def p_generator():

     A. Create a list containing all possible characters for the password.

    pass = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',

                'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',

                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',

                '-', '_', ',', ';', '.', ':', '!', '?', '…', '^', '`', '+', '"', '*', '#', '¶', 'Ç', '%', 'ç', '&', '/',

                '(', ')', '=', '[', ']', '|', '{', '}', 'à', 'ä', 'ö', 'é', '¨', '$', '£', '<', '>', '«', '@', '§', 'æ',

              '¢', '≤', '≥', '¥', '≈', '©', '~', '√', 'è', 'ü', '“', '±', '≠', '¿', '´', 'µ', '~', '∞', 'Ò', 'Ô', 'Ú',

              '∏', 'ÿ', '˚', '◊', '•']

      You can add or remove characters.

     B. Initialize a variable named 'password' and assign it an empty value.

    password = ""

     C. Ask the user for the desired length of the password.

    inp = input("Choose the length of your password(Integer number) : ")

     D. Generate the password by randomly choosing characters from the list.

    for x in range(int(inp)): 

        password = password + random.choices(pass)[0]

     E. Display the password and its length.

  print('Your password is :\n', password)

    # print(len(password), "characters")

     F. Call the function 'save_to_file' to save the password to a text file if the user wishes.

     save_to_file(password)

     G. Return password.

    return password

2. Define the 'save_to_file(password)' function to save the password to a text file. This function contains the following steps:

def save_to_file(password):

     A. Ask the user if they want to save the password.

    save = input("Do you want to register this password ? (y/n) : ")

     B. If yes, Ask the user for the name of the file they want to save the password to.

    if save == 'y':

        file_path = "/Your/Saving/Path/"

        file_name = input("Enter the name of the file to be saved : ")

     C. Check if the file name already contains the ".txt" extension. If not, add the extension.

        # Add ‘.txt’ extension if not already present on file name

        if not file_name.endswith('.txt'):

            file_name = file_name + '.txt'

     D. Open the file in write mode and write the password to it.

        try:

            with open(file_path + file_name, "w") as file:

                file.write(str(password))

     E. Display a message confirming that the password has been saved.

            print("Password saved in the file ", file_name, " in the path :", file_path)

     F. Call the function 'another_action' to allow the user to generate a new password or quit the program.

             another_action()

     G. Add an exception if there is a problem when saving the file

        except IOError:

            print("Error : Error occurred while saving file.")

     H. Elif no, Call function ‘another_action’.

    elif save == 'n':

        another_action()

     J. Else, Add a verification of user input.

    else:

        print("Error : Invalid choice. Enter ‘y’ for yes and ’n’ for no.")

        save_to_file(password)

3. Define the ‘another_action()’ function to offer the user to generate a new password or quit the program. This function contains the following steps:

def another_action():

     A. Ask the user if they want to generate a new password.

    choice = input("Do you want to generate a new password ? (y/n) : ")

     B. If yes, Call the p_generator() function.

    if choice == 'y':

        p_generator()

     C. If no, Display a program-ending message.

    elif choice == 'n':

        print("\nSee you soon  !")

     D. If the user enters anything other than 'y' or 'n', display an error message and call the another_action() function again.

    else:

        print("Error : Invalid choice. Enter ‘y’ for yes and ’n’ for no.")

        another_action()

 

4. Call the 'p_generator()' function to start the program.

p_generator()

Saving these passwords in a text file is not recommended for security reasons. This is for educational purposes only.

Leave a comment if you have any questions

 

If you enjoy my blog posts, you can support me by a tip in my wallet.

Thanks for you support 🫶

 

BTC : bc1qvfmetg2d36mmntrg56ld0tdrte8cqeygjxdpsg

ETH  | USDC | USDT : 0x02AbfBf22fA72d068Ff305e58dF782e58F863274

DOGE : DLtGbPrFvwW5y7jFuvuDAkZGNB2eAErAxA

 

See you soon ! 🤙

Casper_X 👻

 

          Want more programs ?

 

Take a look of these posts.

Scrabble Helper : https://www.publish0x.com/python-scrabble-helper/python-scrabble-helper-xvmqykg

QRcode generator : https://www.publish0x.com/python-scrabble-helper/python-qr-code-generator-xrgmxnx

Face detectionhttps://www.publish0x.com/python-scrabble-helper/python-face-detection-xjrwygy

 

Here is the full program :

 

import random

def p_generator():
    pass = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
                'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
                '-', '_', ',', ';', '.', ':', '!', '?', '…', '^', '`', '+', '"', '*', '#', '¶', 'Ç', '%', 'ç', '&', '/',
                '(', ')', '=', '[', ']', '|', '{', '}', 'à', 'ä', 'ö', 'é', '¨', '$', '£', '<', '>', '«', '@', '§', 'æ',
              '¢', '≤', '≥', '¥', '≈', '©', '~', '√', 'è', 'ü', '“', '±', '≠', '¿', '´', 'µ', '~', '∞', 'Ò', 'Ô', 'Ú',
              '∏', 'ÿ', '˚', '◊', '•']
    password = ""
    inp = input("Choose the length of your password(Integer number) : ")
    for x in range(int(inp)): 
        password = password + random.choices(pass)[0]

    print('Your password is :\n', password)
    # print(len(password), "characters")
    save_to_file(password)
    return password

def save_to_file(password):
    save = input("Do you want to register this password ? (y/n) : ")
    if save == 'y':
        file_path = "/Your/Saving/Path/"
        file_name = input("Enter the name of the file to be saved : ")
        # Add ‘.txt’ extension if not already present on file name
        if not file_name.endswith('.txt'):
            file_name = file_name + '.txt'
        try:
            with open(file_path + file_name, "w") as file:
                file.write(str(password))
            print("Password saved in the file", file_name, " in the path :", file_path)
            another_action()
        except IOError:
            print("Error : Error occurred while saving file.")
    elif save == 'n':
        another_action()
    else:
        print("Error : Invalid choice. Enter ‘y’ for yes and ’n’ for no. ")
        save_to_file(password)


def another_action():
    choice = input("Do you want to generate a new password ? (y/n) : ")
    if choice == 'y':
        p_generator()
    elif choice == 'n':
        # '\n' represents a line break
        print("\nSee you soon !")
    else:
        print("Error : Invalid choice. Enter ‘y’ for yes and ’n’ for no. ")
        another_action()


p_generator()

 

How do you rate this article?

3


Casper_x
Casper_x

Python | Crypto | Javascript | Programming


Python Programs
Python Programs

Tutorials on the programming language 'Python'. In this blog you will find several basics Python programs to complete. Hope you enjoy the content !

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.