How to specify variables with random in Python - python

I am creating a password generator the takes the length of the desired password, number of letters, as well as the number of numbers. The password needs to contain uppercase letters as well as numbers and special characters. I am having trouble figuring out how to specify the number of letters and numbers in the password. This is what I have so far:
import random
charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsnum = "1234567890"
charssym = "!##$%^&*"
def password():
pwd = ""
passlen = int(input("How long do you want the password to be?: "))
passlet = int(input("How many letters do you want in your password?: "))
passnum = int(input("How many numbers do you want in your password?: "))
passsym = int(passlen - (passlet + passnum))
chars = ""
for let in range(passlet):
chars += random.choice(charslet)
for num in range(passnum):
chars += random.choice(charsnum)
for sym in range(passsym):
chars += random.choice(charssym)
for p in range(passlen):
pwd += random.choice(chars)
print(pwd)
password()

I think the last part is what is confusing you. You are building the chars variable with the correct amount of specific chars, but you then choose between them again at the end.
You could just change:
for p in range(passlen):
password += random.choice(chars)
With
# option 1 - works better if working with lists
list_chars = list(chars)
random.shuffle(chars)
password = "".join(list_chars)
# option 2 - simpler solution for strings
password = "".join(random.sample(char, len(char)))
You could also use shuffle to select the chars before without the for loops, something like:
# for this to work your `charslet` must be a list
random.shuffle(charslet)
chars += "".join(charslet[:passlet])

This is the corrected code:
import random
charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsnum = "1234567890"
charssym = "!##$%^&*"
def password():
pwd = ""
passlen = int(input("How long do you want the password to be?: "))
passlet = int(input("How many letters do you want in your password?: "))
passnum = int(input("How many numbers do you want in your password?: "))
passsym = int(passlen - (passlet + passnum))
chars = ""
for let in range(passlet):
chars += random.choice(charslet)
for num in range(passnum):
chars += random.choice(charsnum)
for sym in range(passsym):
chars += random.choice(charssym)
list_chars = list(chars)
random.shuffle(list_chars)
pwd = "".join(list_chars)
print(pwd)
password()
I replaced:
for p in range(passlen):
password += random.choice(chars)
with
list_chars = list(chars)
random.shuffle(list_chars)
pwd = "".join(list_chars)
Putting the altered chars variable in a list allowed me to shuffle it, randomizing it and allowing me to assign it to pwd

Related

Is there a better way to generate a random password?

pass1_1 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1_2 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1_3 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1_4 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1_5 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1_6 = random.choice([random.choice(alphabet)+random.choice(numbers)])
pass1 = pass1_1+pass1_2+pass1_3+pass1_4+pass1_5+pass1_6
print(pass1)
Its python,
Alphabet, number and sc are list made
sure, this is just a loop:
password = "".join(random.choice(alphabet+numbers) for _ in range(6))
Explanation:
alphabet+numbers creates a new string (or list if they are lists) "abc..012"
random.choice picks a random one
the for repeats it for 6 times
the join put them back together
in multiple lines:
password = ""
chars = alphabet+numbers
for _ in range(6):
password += random.choice(chars)

Select characters multiple times with python random

I started to learn python and wanted to do a small project. The project is quite simple. The script should be creating random password with the lenght of user's input. Here the code:
#IMPORTS
from datetime import datetime
import random
#VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&##+*"
passwordConstructor = lowerCase + upperCase + numbers + symbols
userName = str(input("Enter username: "))
passwordLength = int(input("Enter the length of password: "))
f = open(userName.upper() + " - " + dateFormat + ".txt","w+") #generate txt-filename
#GENERATOR
password = "".join(random.sample(passwordConstructor, passwordLength))
#OUTPUT
print(userName + "'s generated password is: " + password)
f.write("USERNAME: " + userName + "\nPASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
f.close()
But here the characters where choosed just once. But how do I get it done, so for example the letter "a" can be choosed multiple time.
Usecase:
NOW
I enter password length 7. The output would be: "abc1234" (of course random order)
EXPECTED
I enter password length 10. The output should be: "aaabcc1221" (of course random order)
Thanks for the help!
I think you can use random.select n times where n is the length of the password instead and then join all the selected values into a string
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])

How do I print my password in 1 string and display it to the user?

I have created a random password generator and it works but it displays "Here is your randomly generated password" for every character that it outputs. I would like it to put the full password in 1 string and display it to the user. Any help would be much appreciated.
import random
def password_generator():
length = int(input("Input length of password: "))
for n in range(length):
symbol_number = random.randint(33, 58)
character = random.randint(65, 123)
password = chr(symbol_number or character)
print(f"Here is your randomly generated password \nPassword: {password}")
password_generator()
One method you could use is to collect each item from the for loop inside a list and then join the list items together as a string before you display them to use user.
import random
def password_generator():
length = int(input("Input length of password: "))
password = []
for n in range(length):
symbol_number = random.randint(33, 58)
character = random.randint(65, 123)
password.append(chr(symbol_number or character))
password = "".join(password)
print(f"Here is your randomly generated password \nPassword: {password}")
password_generator()
What is the intended purpose of the or operator? I don't think it is going to do what you expect it to.
it displays "Here is your randomly generated password" for every character that it outputs.
That's because you have incorrectly indented your last line. It should be outside the for loop, not inside. You can fix it like so:
def password_generator():
length = int(input("Input length of password: "))
password = ""
for n in range(length):
symbol_number = random.randint(33, 58)
character = random.randint(65, 123)
password = password + chr(symbol_number or character)
print(f"Here is your randomly generated password \nPassword: {password}")

Python Password Generatr with read and random module

im kinda new to python and am programming a password generator. As of now, i think i am at a plateau where i need explanation.
At the end, where i want to generate a password with the user input given above, i get a type error
(TypeError: choice() takes 2 positional arguments but 3 were given)
What am I missing, so that the random.choice function is not working
import random
Uppercaseletters = open("Upper.txt").read()
Lowercaseletters = open("Lower.txt").read()
Numbers = open("Zahlen.txt").read()
Symbols = open("Symbole.txt").read()
Upperbool = True
Lowerbool = True
Numbersbool = True
Symbolsbool = True
whole = ""
if Upperbool:
whole += Uppercaseletters
if Lowerbool:
whole += Lowercaseletters
if Numbersbool:
whole += Numbers
if Symbolsbool:
whole += Symbols
print("Hello and welcome to the simple password generator.")
a = 1
b = 1
if b <= 10:
amount = int(input("How many passwords do you want to generate? "))
else:
print("You are exceeding the limit of a maximum of 10 Passwords")
# length auswählen lassen (maximal 20 Zeichen lang (Fehler prevention))
if a <= 20:
length = int(input("How long do you want your password to be? "))
else:
print("That password will be too long, try a number below 20")
for x in range(amount):
password = "".join(random.choice(whole, length))
print(password)
I believe you are looking for something like this:
import random
Uppercaseletters = open("Upper.txt").read()
Lowercaseletters = open("Lower.txt").read()
Numbers = open("Zahlen.txt").read()
Symbols = open("Symbole.txt").read()
Upperbool = True
Lowerbool = True
Numbersbool = True
Symbolsbool = True
whole = ""
if Upperbool:
whole += Uppercaseletters
if Lowerbool:
whole += Lowercaseletters
if Numbersbool:
whole += Numbers
if Symbolsbool:
whole += Symbols
print("Hello and welcome to the BMD's simple password generator.")
amount = 100
length = 100
while amount>10:
amount = int(input("How many passwords do you want to generate? "))
if amount>10:
print("You are exceeding the limit of a maximum of 10 Passwords")
while length>20:
length = int(input("How long do you want your password to be? "))
if length>20:
print("That password will be too long, try a number below 20")
for passwords in range(amount):
password = ""
for character in range(length):
password = password + random.choice(list(whole))
print(password)
I modified it so that it does not allow amounts above 10 and lengths above 20.

How to remove characters from a specific place in a string(not by index) in Python

So I have this code:
def myprogram():
import string
import random
import getpass
inputpasswd = getpass.getpass("Password: ")
passwd = ("I<3StackOverflow")
if passwd == inputpasswd:
qwerty = input("Type something: ")
def add_str(lst):
_letters = ("1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","z","u","i","o","p","a","s","d","f","g","h","j","k","l","y","x","c","v","b","n","m","!","#","$","%","&","/","(",")","=","?","*","+","_","-",";"," ")
return [''.join(random.sample(set(_letters), 1)) + letter + ''.join(random.sample(set(_letters), 1))for letter in lst]
print(''.join(add_str(qwerty)))
input("")
else:
print("Wrong password")
input("")
My question is: How can I make an opposite program, so it accepts the bunch of junk letters and converts it to text that makes sense?
Example:
If I type something like "aaaaaaa" in this program it will convert it to something like "mapma&)at7ar8a2ga-ka*"
In this new program I want to type "mapma&)at7ar8a2ga-ka*" and get output "aaaaaaa".
Does this work for you?:
s="1a23a45a6"
print(s[1::3]) # aaa
Do so: initial_str = random_str[1:-1:3], where random_str is string with junk

Categories