|
| 1 | +# Import required modules |
1 | 2 | import random
|
2 | 3 | import string
|
3 | 4 |
|
| 5 | +# Define function to generate password |
4 | 6 | def generate_password(min_length, numbers=True, special_characters=True):
|
| 7 | + # Define character sets to be used for generating password |
5 | 8 | letters = string.ascii_letters
|
6 | 9 | digits = string.digits
|
7 | 10 | special = string.punctuation
|
8 | 11 |
|
| 12 | + # Determine which character sets to use based on user input |
9 | 13 | characters = letters
|
10 | 14 | if numbers:
|
11 | 15 | characters += digits
|
12 | 16 | if special_characters:
|
13 | 17 | characters += special
|
14 | 18 |
|
| 19 | + # Initialize variables for password generation and criteria checking |
15 | 20 | pwd = ""
|
16 | 21 | meets_criteria = False
|
17 | 22 | has_number = False
|
18 | 23 | has_special = False
|
19 | 24 |
|
| 25 | + # Loop until password meets criteria and is long enough |
20 | 26 | while not meets_criteria or len(pwd) < min_length:
|
| 27 | + # Generate a new random character and add it to the password |
21 | 28 | new_char = random.choice(characters)
|
22 | 29 | pwd += new_char
|
23 | 30 |
|
| 31 | + # Check if the new character is a number or special character |
24 | 32 | if new_char in digits:
|
25 | 33 | has_number = True
|
26 | 34 | elif new_char in special:
|
27 | 35 | has_special = True
|
28 | 36 |
|
| 37 | + # Determine if the password meets the specified criteria |
29 | 38 | meets_criteria = True
|
30 | 39 | if numbers:
|
31 | 40 | meets_criteria = has_number
|
32 | 41 | if special_characters:
|
33 | 42 | meets_criteria = meets_criteria and has_special
|
34 | 43 |
|
| 44 | + # Return the generated password |
35 | 45 | return pwd
|
36 | 46 |
|
| 47 | +# Get user input for password criteria |
37 | 48 | min_length = int(input("Specify the minimum length required for the password. "))
|
38 | 49 | has_number = input("Do you want the password to include numbers? (y/n)").lower() == "y"
|
39 | 50 | has_special = input("Do you want the password to include special characters? (y/n)").lower() == "y"
|
| 51 | + |
| 52 | +# Generate and print the password |
40 | 53 | pwd = generate_password(min_length, has_number, has_special)
|
41 | 54 | print ("Here is the password generated: ", pwd)
|
0 commit comments