-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassword_generator.py
More file actions
54 lines (39 loc) · 2.18 KB
/
password_generator.py
File metadata and controls
54 lines (39 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import string
import random
import sys
# Creates a function that accepts an argument representing the length of the password
def generate_password(length):
# Creates a variable to hold commonly accepted special characters/punctuations for passwords
accepted_specialchar = "!@#$%^&*_-+=<>?~"
# Assigns characters from ascii_letters (all upper/lower), digits (all numbers), and `accepted_specialchar` into `characters`
# The reason string.printable is not used is due to inclusion of white space
characters = string.ascii_letters + string.digits + accepted_specialchar
# Uses a list comprehension to join a random character from `characters` each time i iterates within the range of `length`
password = "".join(random.choice(characters) for i in range(length))
# Returns the value for `password`
return password
run_flag = True
# While `run_flag` is set to True, continue to prompt user
while run_flag:
print("Enter how many characters you would like your generated password to have, or enter Q to quit")
# Takes user's input and store into `length`
length = input()
# Checks if `length` value is a positive integer
if length.isdigit() and int(length) > 0:
# Converts value for `length` from string to int type
length = int(length)
# Calls the generate_password function, passes in `length`, and stores the returned value into `password`
password = generate_password(length)
# Prints the value for `password`
print(f"Your generated password is: {password}")
# Sets `run_flag` to False which breaks the While loop
run_flag = False # Alternative: sys.exit()
# Checks if `length` value is equal to Q
elif length.upper() == "Q":
# Prints a statement indicating the script is quitting
print("...Quitting...")
# Sets `run_flag` to False which breaks the While loop
run_flag = False # Alternative: sys.exit()
# Accounts for other error conditions and restarts the loop block
else:
print("Invalid input. Please enter a positive number or Q to quit")