This project will guide you through creating a simple password generator using Python. The program will ask the user if they want to generate a password, and if the user agrees, it will generate a random password based on the specified length.
Before you start, make sure you have Python installed on your system. If not, you can download it from here.
First, we need to import the required libraries for our project. We will use the string
and random
libraries.
import string
import random
We need to define a list of characters that our password can include. This includes uppercase and lowercase letters, digits, and some special characters.
characters = list(string.ascii_letters + string.digits + "!@#$%^&*&?/.,()")
Next, we will define a function generate_password
that will generate a random password based on the user's specified length.
def generate_password():
password_length = int(input("How long would you like your password to be? "))
random.shuffle(characters)
password = []
for x in range(password_length):
password.append(random.choice(characters))
random.shuffle(password)
password = "".join(password)
print(password)
We will prompt the user to decide if they want to generate a password. Based on their input, we will either generate the password or exit the program.
option = input("Do you want to generate a password (Y/N): ")
if option == "Y":
generate_password()
elif option == "N":
print("Okay, no problem. Have a great day!")
else:
print("Invalid option. Please try again.")
quit()
Here is the complete code for the password generator project:
import string
import random
characters = list(string.ascii_letters + string.digits + "!@#$%^&*&?/.,()")
def generate_password():
password_length = int(input("How long would you like your password to be? "))
random.shuffle(characters)
password = []
for x in range(password_length):
password.append(random.choice(characters))
random.shuffle(password)
password = "".join(password)
print(password)
option = input("Do you want to generate a password (Y/N): ")
if option == "Y":
generate_password()
elif option == "N":
print("Okay, no problem. Have a great day!")
else:
print("Invalid option. Please try again.")
quit()
To run the code, save it in a file named password_generator.py
and execute it using the command:
python password_generator.py
Follow the prompts to generate your password.