I am trying to create a password generator in Python that must contain an uppercase letter, lowercase letter, and a number, and must have a length between 6 and 20 characters.
import random
import string
def password_gen():
while True:
length = random.randint(6,20)
pwd = []
for i in range(length):
prob = random.random()
if prob < 0.34:
char = random.choice(string.ascii_lowercase)
pwd.append(char)
elif prob < 0.67:
char = random.choice(string.ascii_uppercase)
pwd.append(char)
else:
char = str(random.randint(0,9))
pwd.append(char)
pwd = ''.join(pwd)
#check password here
return pwd
However, I am having trouble checking the password to make sure it contains the required characters listed earlier. I am not sure if/how i would use a continue statement.Any help would be greatly appreciated!
I think this would be a bit easier to ensure you meet the base requirements if you just handle those upfront.
import random
import string
def generate_pw():
length = random.randint(6,20) - 3
pwd = []
pwd.append(random.choice(string.ascii_lowercase))
pwd.append(random.choice(string.ascii_uppercase))
pwd.append(str(random.randint(0,9)))
# fill out the rest of the characters
# using whatever algorithm you want
# for the next "length" characters
random.shuffle(pwd)
return ''.join(pwd)
This will ensure your password has the characters you need. For the rest of the characters you could for example just use a list of all alphanumeric characters and call random.choice length times.
you can use isupper() and islower() functions to get does your password contain uppercase and lowercase.
e.g.
upper=0
lower=0
for i in range(length):
if (pwd[i].islower()):
upper=1
elif (pwd[i].isupper()):
lower=1
import random
import string
def password_gen():
lower_case_letter = random.choice(string.ascii_lowercase)
upper_case_letter = random.choice(string.ascii_uppercase)
number = random.choice(string.digits)
other_characters = [
random.choice(string.ascii_letters + string.digits)
for index in range(random.randint(3, 17))
]
all_together = [lower_case_letter, upper_case_letter] + other_characters
random.shuffle(all_together)
return ''.join(all_together)
Password Generator more broken down, you can get any number you wish, but it outputs a pattern by first adding letters, then numbers and finally symbols
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
passwordlength = nr_letters + nr_numbers + nr_symbols
chars = ""
for x in range (0, nr_letters):
char = random.choice(letters)
chars += char
nums = ""
for y in range (0, nr_numbers):
num = random.choice(numbers)
nums+=num
syms = "" # string accumulator
for z in range (0, nr_symbols):
symb = random.choice(symbols)
syms += symb
print(f"Here is your password: {chars}{nums}{syms}")
Related
#Password Generator Project
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
password = []
for l in range (0 , nr_letters+1):
random_l = random.choice(letters)
password.append(random_l)
for i in range (0 , nr_symbols+1):
random_i = random.choice(symbols)
password.append(random_i)
for n in range (0 , nr_numbers+1):
random_n = random.choice(numbers)
password.append(random_n)
print(random.choice(password))
I want to randomize and print the password list at the end of the code but it gives me only one character. When I print it without random function or shuffle it prints properly.
In OP's question password is a list (a sequence). random.choice() selects a single pseudo-random item from a sequence. Thus you get just one character.
Using random.choices() simplifies the entire process
from random import choices, shuffle
from string import ascii_lowercase, digits
symbols = '!#$%&()*+'
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password? "))
nr_symbols = int(input("How many symbols would you like? "))
nr_numbers = int(input("How many numbers would you like? "))
password = choices(ascii_lowercase, k=nr_letters)
password += choices(digits, k=nr_numbers)
password += choices(symbols, k=nr_symbols)
shuffle(password)
print(''.join(password))
Example:
Welcome to the PyPassword Generator!
How many letters would you like in your password? 6
How many symbols would you like? 2
How many numbers would you like? 2
bf%t6vf(g0
random.choice(password) just picks a random item from password. Use random.shuffle(password) to shuffle it.
random.shuffle(password)
print("".join(password))
Changes made
(1) you are taking one character extra in each of them.. Corrected!
(2) created a variable res_in_str which is string storing the password generated
(3) created a variable res_in_list which is list storing the password generated in list format
Code:-
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
password = []
for l in range (0 , nr_letters):
random_l = random.choice(letters)
password.append(random_l)
for i in range (0 , nr_symbols):
random_i = random.choice(symbols)
password.append(random_i)
for n in range (0 , nr_numbers):
random_n = random.choice(numbers)
password.append(random_n)
res_in_str=""
res_in_list=[]
while len(password):
char=random.choice(password)
password.remove(char)
res_in_str+=char
res_in_list.append(char)
print("Password Generated: ",res_in_str)
print("Password Generated in list format: ",res_in_list)
Output:-
Welcome to the PyPassword Generator!
How many letters would you like in your password?
6
How many symbols would you like?
3
How many numbers would you like?
3
Password Generated: ZIL!0cy#r25#
Password Generated in list format: ['Z', 'I', 'L', '!', '0', 'c', 'y', '#', 'r', '2', '5', '#']
This is how I would solve it:
from string import ascii_letters, digits, punctuation
from random import choice, shuffle
def selector(quantity, type):
return(return([choice([x for x in type]) for _ in range(0, quantity)]))
print("Welcome to the PyPassword Generator!")
nr_letters= selector(int(input("How many letters would you like in your password?\n")), ascii_letters)
nr_symbols = selector(int(input(f"How many symbols would you like?\n")), punctuation)
nr_numbers = selector(int(input(f"How many numbers would you like?\n")), digits)
temp_password = nr_letters+nr_symbols+nr_numbers
shuffle(temp_password)
password = "".join(temp_password)
print(password)
Results:
Welcome to the PyPassword Generator!
How many letters would you like in your password?
8
How many symbols would you like?
4
How many numbers would you like?
2
1IEa>L'cBSR_^9
Welcome to the PyPassword Generator!
How many letters would you like in your password?
8
How many symbols would you like?
0
How many numbers would you like?
6
bJOV06DR340Y4S
Your code
Your code is correct down to the last row in the print function.
Instead, you should use the join string method like this :
print(password)
# ['s', 'F', 'h', 'i', 'b', 'f', '*', '$', '(', '&', '(', '$', '4', '4', '6', '2', '4', '2']
# So you could use for instance the join function combined with
# random to reconstitue a readable randomized password
print(''.join(random.sample(password, k=len(password))))
# s$($b4(24&2Fhf64*i
The fact is that, by using the choice function in the print row, you ask for returning a unique randomized letter from your password.
My proposal
Indeed, I proposed you the following code instead :
from random import sample
from string import ascii_uppercase, digits
symbols = '!#$%&()*+'
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
agg_s = sample(ascii_uppercase, nr_letters)
agg_s += sample(symbols, nr_letters) # or string.punctuation instead symbols
agg_s += sample(digits, nr_numbers)
password = ''.join(sample(agg_s, k=len(agg_s)))
print("password : " , password)
# password : 9E6XC%P&$24J1(!
Note :
Taking a same length randomized sample from a sample is equivalent to a randomized permutation.
So no matter if the variable agg_s is followed by letters, and then respectively by symbols and digits.
When you are using sample(k, len(k)) to reorganize agg_s, you effectively have a randomized password.
#Password Generator Project
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
#Eazy Level - Order not randomised:
#e.g. 4 letter, 2 symbol, 2 number = JduE&!91
def my_function():
for i in range(1,nr_letters+1):
variable=random.choice(letters)
print(variable, end='')
for j in range(1,nr_symbols+1):
variable1=random.choice(symbols)
print(variable1, end='')
for k in range(1,nr_numbers+1):
variable2=random.choice(numbers)
print(variable2, end='')
#Hard Level - Order of characters randomised:
#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P
#my_function()
function_to_list=my_function()
print[(function_to_list)]
shuffle_my_function=random.shuffle(function_to_list)
print(shuffle_my_function)
This is a kind of personal project here my task is to generate a password. On the easy level just print the password sequence wise whereas on the hard level I want my password to be shuffled.
My easy level code is working perfectly but on the hard level, I want to shuffle the result of the easy level for that I thought that if I define a function of the easy part and then somehow convert that function into the list I can easily use shuffle function . so please help me. please try to do give a solution in my way of thinking and then please suggest your way of doing it
This is a common beginner problem. When you print something, it's there on the screen, but only as text. And the program can't see that text. You have to do something to the variables to keep track of them as you go. In this case, you need to append them to a list. Not only that, but you need to return the list to the caller, so that function_to_list = my_function() assigns something other than None to function_to_list:
def my_function():
list_of_characters = []
for i in range(nr_letters):
list_of_characters.append(random.choice(letters))
for j in range(nr_symbols):
list_of_characters.append(random.choice(symbols))
for k in range(nr_numbers):
list_of_characters.append(random.choice(numbers))
return list_of_characters
Notice that I took out the print statements. That's because a function should do only one thing and do it well. You can print your list and your password as soon as you get them back:
list_from_function = my_function()
print(list_from_function)
To print the list as a single string, join the letters it contains with the emtpy string:
print(''.join(list_from_function))
You can shuffle the result, or do whatever you want:
random.shuffle(list_from_function)
print(list_from_function)
Keep in mind that shuffle operates in place and returns None. That means that if you try to print its return value, you get nothing.
You don't need to use for loop. You can pass argument to random.choices() indicating how many items you want.
import random
import string
letters = string.ascii_letters
numbers = string.digits
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
# For demo, I hardcoded the numbers
nr_letters = 4
nr_symbols = 5
nr_numbers = 3
# create a list from randomly choosen characters
password_characters = random.choices(letters, k = nr_letters) \
+ random.choices(symbols, k = nr_symbols) \
+ random.choices(numbers, k = nr_numbers)
# shuffle the list:
random.shuffle(password_characters)
# convert the list to string
password = ''.join(password_characters)
Output:
>>> print(password)
>>> &J0*4oR!I3$!
I'm taking a 100 Days of Code in Python, and I'm trying to create a Python password generator by taking in user input for how many letters, numbers, and symbols they'd like in their password.
The program below runs and generates the desired output, but I know there must be a better way than iterating over the range an arbitrary number of times to generate a fixed-length password.
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input('How many letters would you like in your password?: '))
nr_symbols = int(input('How many symbols would you like?: '))
nr_numbers = int(input('How many numbers would you like?: '))
password = ""
# Generate unshuffled password
# for i in range(1, (nr_letters + 1)):
# password += random.choice(letters)
# for i in range(1, (nr_symbols + 1)):
# password += random.choice(numbers)
# for i in range(1, (nr_numbers +1)):
# password += random.choice(symbols)
# print(password)
letter_counter = 0
symbol_counter = 0
number_counter = 0
# NOTE: This seems dumb but it works so...
for i in range(0, 100):
random_int = random.randint(0, 2)
if random_int == 0 and letter_counter < nr_letters:
password += random.choice(letters)
letter_counter += 1
elif random_int == 1 and symbol_counter < nr_symbols:
password += random.choice(symbols)
symbol_counter += 1
elif random_int == 2 and number_counter < nr_numbers:
password += random.choice(numbers)
number_counter += 1
print(password)
Is there a cleaner way I can create a shuffled, fixed-length string through a Python for loop?
For the future, is there a major downside to iterating through a loop more times than it takes to generate the desired output?
I think this is what you are looking for?:
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input('How many letters would you like in your password?: '))
nr_symbols = int(input('How many symbols would you like?: '))
nr_numbers = int(input('How many numbers would you like?: '))
password = ""
for i in range(1, sum([nr_letters,nr_numbers,nr_symbols])+1):
if i<= nr_letters:
password += random.choice(letters)
elif i > nr_letters and i<=nr_symbols+nr_letters:
password += random.choice(symbols)
elif i > nr_symbols+nr_letters:
password += random.choice(numbers)
password=[x for x in password]
random.shuffle(password)
password="".join(password)
print(password)
Basically, instead of iterating through an arbitrary number, it adds up the number of characters required, then it goes through the range, and adding the numbers/symbols/letters when the requirements are met.
The requirements are basic. While below or equal to the number of letters required, add a letter. Then, you go and add the number of letters and symbols together, and say that it has to meet both above the number of letters, and below letters+symbols. Then, if i is above letters+symbols, add numbers. That's pretty much the pattern.
The downside is that you will have to shuffle afterwards like I've done above. password=[x for x in password] basically turns password into a list. Then you shuffle it with random.shuffle(password), and then join it password="".join(password).
It's basically your first commented out iterations bundled up in 1.
So basically what I want to do is if the random string of characters generated is over 6 chars long it adds a space in a random place in that string and then the remaining ones are added on after the space so for example: raw output: "aoneicse", what I want : "aoneic se" or "aone icse".
Here is my code:
import random
alist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
blist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
clist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define the 3 words
a = ''.join(random.choices(alist, k = random.randint(2,8)))
b = ''.join(random.choices(blist, k = random.randint(2,8)))
c = ''.join(random.choices(clist, k = random.randint(2,8)))
# each letter is a certain word, if this word exceeds 6 characters add a space in a random place
if a length = > 6:
asp = [a + " "]
if b length = > 6:
bsp = [b + " "]
if c length = > 6:
csp = [c + " "]
# or something along the lines of this i guess
This code does not currently work, BTW.
You don't need to create a list of strings with every letter of the alphabet, there's already a string module that does that for you:
import string
print(' ' + string.ascii_lowercase)
# Outputs abcdefghijklmnopqrstuvwxyz
You also don't need to create three different variables, you can just use a single one and use that:
import string
base_str = ' ' + string.ascii_lowercase
Then, you can use a list to generate your words based on this string:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
Now, just apply your space requirement to each word:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
new_words = []
for word in words:
if len(word) < 6:
new_word = word
else:
pos = random.randrange(len(word))
new_word = word[:pos] + ' ' + word[pos:]
new_words.append(new_word)
Using random.seed(0), new_words is equal to ['j xazmxvz', 'oxmg', 'buzns pcb'].
Don't join the choices immediately. Generate the list, and if it is long enough, pick an index in the middle (sufficiently far from either end, depending on your needs), and perform a slice assignment to the empty list at that position. Then join the list into a single string.
import string
a = random.choices(string.ascii_lowercase, k=random.randint(2,8))
if len(a) > 6:
# Adjust the arguments to randint as desired
x = random.randint(2, len(a) - 2)
a[x:x] = ' '
a = ''.join(a)
import random
character = list(map(chr, range(ord('a'), ord('z') + 1)))
def get_char():
return character[random.randint(0, len(character) - 1)]
def gen_word(min_len, max_len):
word = [get_char() for _ in range(random.randint(min_len, max_len))]
if len(word) > 6:
word[random.randint(1, len(word) - 2)] = ' '
return ''.join(word)
for i in range(10):
print(gen_word(4, 10))
Iād use slices to return a space, sliced-in at the right spot; Something along the lines of:
def split(input_str):
if len(input_str) > 6:
space_at = rand(0,len(input_str))
return input_str[:space_at] + ā ā + input_str[space_at:]
else:
return input_str
Currently the code only randomized in sequence , first letters then numbers and lastly symbols i would like it to randomized in any order without sequence , how to implement?
#Password Generator Project
import string
import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
l_password = ""
s_password = ""
n_password = ""
# Eazy Level - Order not randomised:5
# e.g. 4 letter, 2 symbol, 2 number = JduE&!91
for letter in range(nr_letters):
l_password += random.choice(letters)
for symbol in range(nr_symbols):
s_password += random.choice(symbols)
for number in range(nr_numbers):
n_password += random.choice(numbers)
final_pass = str(l_password) + str(s_password) + str(n_password)
print(f"Here is your password :{final_pass}")
#Hard Level - Order of characters randomised:
#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P
You can use random.shuffle to shuffle the result:
final_pass = str(l_password) + str(s_password) + str(n_password)
l = list(final_pass)
random.shuffle(l)
final_pass = ''.join(l)
You can use random.sample()
import random
password = "123435454"
password = ''.join(random.sample(password, len(password)))
print(password)