input isn't choosing the passwort length - python

I'm new to programming, and I'm making a password manager.
My problem: -what it does -> when I run the program and enter the length of the password it generates a password, but it is always 4 digits long and the password gets repeated so many times as the digit I had put in.
-What it should do -> the digit that I put in should determine the length of the password and not how many times it gets repeated.
import random
#shuffle the list
def shuffle(string):
tempList = list(string)
random.shuffle(tempList)
return ''.join(tempList)
#the password functions
uppercaseLetter=chr(random.randint(65,90))
lowercaseLetter=chr(random.randint(97,122))
punctuationSign=chr(random.randint(32,152))
digit=chr(random.randint(48,57))
#completing the password
passwordLength = int(input("choose your password length: "))
possibleChars = uppercaseLetter, lowercaseLetter, punctuationSign, digit
ranChar = shuffle(possibleChars)
tempPassword = []
count = 0
while count != passwordLength:
tempPassword.extend(ranChar)
count = count + 1
password = ''.join(tempPassword)
#for which sitename
sitename = input('Save under which name: ')
print (password, sitename)
data=open("test.txt",'a')
data.write(sitename +' ')
data.write(password +'\n')
data.close()

I think you are really over complicating what you need to do, here is what you're trying to do to the best of my knowledge
import random
#completing the password
passwordLength = int(input("choose your password length: "))
temp_pass = ''
count = 0
while count != passwordLength:
char_type = random.randint(0,3)
if char_type == 0:
random_char = chr(random.randint(65,90))
elif char_type == 1:
random_char = chr(random.randint(97,122))
elif char_type == 2:
random_char = chr(random.randint(32,152))
else:
random_char = chr(random.randint(48,57))
temp_pass = temp_pass + random_char
count = count + 1
print(temp_pass)
Hope this helps. I would advise practicing the basics more before trying things like this, there is a lot of bad practises in the code.

Related

(Python3) - Random number inserted at the end of only 1 word in a string of many words

I am trying to make a random word/phrase generator that is like the one that bitwarden has (in python3). But the issue I am running into and need some help with is the addition of 1 number at the end of 1 of the words that is shown.
Something like this Referee-Outrank-Cymbal-Cupping-Cresting-Fiber7-Expensive-Myth-Unveiling-Grasp-Badland-Epiphany-Simplify-Munchkin-Pastrami-Spiffy-Gladly-Skeptic-Retouch-Buckskin
What is very important here is that the number is "random" and the word it is attached to is "random".
Code I have written so far:
Word list I am using is https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain but without ' in any of the words.
#pycryptodome==3.15.0
from Crypto.Random import random
import beaupy
import os
def clear():
os.system('clear||cls')
def main():
while True:
try:
number = int(beaupy.prompt("How many words?: "))
except ValueError as e:
print(f'Oops! Something went wrong.\nError: {e}\n\n')
input('Press "enter" to continue...')
clear()
continue
if number > 20 or number < 3:
print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
input('Press "enter" to continue...')
clear()
else:
break
cwd = os.getcwd()
word_path = f"{cwd}/words.txt"
with open(word_path, 'r') as fh:
words = fh.read().lower()
word_list = words.splitlines() #list of words
sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
if sep == '' or sep == ',':
sep = '-'
#Returns True or False. Basically Yes or No?
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
c_lst.append(i.title())
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
#I don't know what to do here... but I need to have a version with the number and one without. (default)
if __name__ == '__main__':
clear()
main()
I am not exactly familiar with string manipulation and searching for answers online just isn't giving me any help with the very specific thing I'm trying to do. All I want is for 1 word in the resulting string to have a "random" number attached to it.
I don't know if I need to re order my code and have it be done a different way. I am having such a headache with this. Any help would be great.
Edit#1
Additional and unrelated note, If anyone knows of a better word list to use, please let me know!
If I am understanding correctly, here is a solution:
#Returns True or False. Basically Yes or No?
capital_words = ''
default_words = ''
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
c_lst.append(i.title())
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
#I don't know what to do here... but I need to have a version with the number and one without. (default)
word_index = random.randint(0, number - 1) # Get random index that is in the word list
if default_words != '':
word_with_number = default_words.split(sep)
else:
word_with_number = capital_words.split(sep)
word_with_number[word_index] = word_with_number[word_index] + str(rn_num)
word_with_number = sep.join(word_with_number)
print(word_with_number)
if default_words != '':
print(default_words)
else:
print(capital_words)
OUTPUT:
detroit-elide-windbag-purge-tort-mortician-codex7-annex-fairy-suntanning
detroit-elide-windbag-purge-tort-mortician-codex-annex-fairy-suntanning
With some help from AnonymousFrog. I was able to get my code working.
The following is the now working code.
from Crypto.Random import random
import beaupy
import os
def clear():
os.system('clear||cls')
def main():
while True:
try:
number = int(beaupy.prompt("How many words?: "))
except ValueError as e:
print(f'Oops! Something went wrong.\nError: {e}\n\n')
input('Press "enter" to continue...')
clear()
continue
if number > 20 or number < 3:
print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
input('Press "enter" to continue...')
clear()
else:
break
cwd = os.getcwd()
word_path = f"{cwd}/words.txt"
with open(word_path, 'r') as fh:
words = fh.read().lower()
word_list = words.splitlines() #list of words
sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
if sep == '' or sep == ',':
sep = '-'
#Returns True or False. Basically Yes or No?
capital_words = ''
default_words = ''
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
if len(i) < 3 or len(i) > 9:
pass
else:
c_lst.append(i.title())
cap = True
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
cap = False
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
num = True
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
word_index = random.randint(0, number - 1) # Get random index that is in the word list
if default_words != '':
word_with_number = default_words.split(sep)
else:
word_with_number = capital_words.split(sep)
word_with_number[word_index] = word_with_number[word_index] + str(rn_num)
word_with_number = sep.join(word_with_number)
else:
num = False
if cap == True and num == False:
print(capital_words)
if cap == False and num == False:
print(default_words)
if num == True:
print(word_with_number)
Thanks for the help!
(if anyone knows of a better word list to use, feel free to let me know)

Unstable password, is there a better way to generate passwords?

import random
import string
lowercase = [string.ascii_lowercase]
uppercase = [string.ascii_uppercase]
number = [string.digits]
symbols = [string.punctuation]
password_outputs = string.ascii_lowercase + string.ascii_uppercase + string.digits +string.punctuation
I was wondering if there was a better way to create a more secure password then just using the ascii strings with random
Done following changes in your code.
import random
import string
lowercase = [string.ascii_lowercase]
uppercase = [string.ascii_uppercase]
number = [string.digits]
symbols = [string.punctuation]
password_outputs = string.ascii_lowercase + string.ascii_uppercase + string.digits +string.punctuation
print("Welcome to the RPG!")
gen_password=''
stop = False
num_char = 0. # include this line if you want that earlier user entered 3 and in next iteration 5 so total you want 8 character password if you only want 5 character password then you can remove this line
while not stop:
gen_password='' # each time it will default to empty
num_char += int(input('Enter in the ammount of characters for the desired password: '))
while num_char > 0:
rand_char = random.choice(password_outputs)
gen_password += rand_char
num_char -= 1
#basically a redstone repeater that decreases in value until it hits 0 and can contiue. User able to pick start value
if num_char == 0:
print(gen_password)
#ensures that only the final product of while loop is printed
#if num_char != int:
#stop = False
#want to make it more secure against non-integer inputs, not sure how to go about this
user_continue = input('Would you like to generate a longer password? (y/n): ')
if user_continue == 'y':
stop = False
elif user_continue == 'n':
stop = True
else:
print('Invalid Operation, running generator again')
stop = False
print("Have a nice day!")

creating a program that needs to check if 2 lists match completely but not working for some reason

I need to check whether 2 lists match in order, e.g. ['h', 'i', '2'] and ['h', 'i', '2'] would be a match.
I am trying a range of things and am trying list1 == list2 but that doesnt work for some reason and im not too sure why.
I have also tried collection counters and that did work but it also worked for lists that werent in order so not useful
I have had to do some wierd layout stuff by changing it from tuples to lists but the lists match completely, they are just not flagged when they do match.
class passwordCracker:
def __init__(self, password):
self.password = password
self.characters = []
self.passwordLength = len(password)
def characterFinder(self):
letters = string.printable
letters = [char for char in letters]
start = time.time()
with open("common_passwords.csv") as f: #cracking password using a dictionary attack
reader = csv.reader(f)
commonWords = list(reader) #putting common passwords in a list
passwordList = [self.password]
print(passwordList)
counter = 0
found = False
for i in range(len(commonWords)): #looping through common passwords
lengthOfList = len(commonWords)
if commonWords[i] == passwordList: #if passwords match
print("password cracked: " + self.password)
end = time.time()
print(f"Password cracked in {end - start}") #print message
found = True
break #break from for loop
else:
counter = counter + 1
if counter == lengthOfList: #if end of list reached
break #break from for loop
# passwordSplit = [char for char in self.password]
passwordTuple = tuple(self.password)
count = 0
checker = 0
if found == False:
for i in range(0, len(letters)+1):
for x in itertools.combinations(letters, i):
if found == False:
count=count+1
print(count)
passwordTuple = list(passwordTuple)
print(passwordTuple)
variable = list(x)
print(variable)
if passwordTuple == variable:
for i in range(1000000):
print("HELLO")
print("password cracked: " + self.password)
end = time.time()
print(f"Password cracked in {end - start}") # print message
found = True
break # break from for loop
password = input("Please enter the tested password: ")
test2 = passwordCracker(password)
test2.characterFinder()
example list below
An easier way to do this could be by sorting the lists and then using Collections counter. Make sure you import collections
list1.sort()
list2.sort()
if collections.Counter(list1) == collections.Counter(list2):
print ("The lists are identical")
else :
print ("The lists are not identical")

password generator - letter check

I am trying to build a password generator that would give me passwords that consist of lower case, upper case, numbers and special characters. Below is my code. It generates passwords to the required length but these do not contain characters from each group. Please can someone help to explain what I did wrong?
Many thanks.
import random
lower_case = list("abcdefghijklmnopqrstuvwxyz")
upper_case = list("abcdefghijklmnopqrstuvwxyz".upper())
num = []
for i in range(0, 10):
num.append(i)
s_letters = ["_", "#", "."]
available_char = lower_case + upper_case + num + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
try:
int(user_l) >= 6
except:
print("invalid number")
length()
return int(user_l)
def password_gen(x):
password = []
for i in range(x):
character = random.choice(available_char)
password.append(str(character))
set_a = set(password)
while True:
valid = True
if set_a & set(lower_case) == {}:
password_gen(x)
valid = False
if set_a & set(upper_case) == {}:
password_gen(x)
valid = False
if set_a & set(num) == {}:
password_gen(x)
valid = False
if set_a & set(s_letters) == {}:
password_gen(x)
valid = False
if valid:
print("Your password is " + "".join(password))
print(set_a & set(lower_case))
print(set_a & set(upper_case))
print(set_a & set(num))
print(set_a & set(s_letters))
break
set_password()
Perhaps you could create another list of keys corresponding to each character type (e.g. char_type = [“number”, “special”, “lowercase”, “uppercase”]). Then, prior to choosing a random item from one of those lists, you can randomly choose an item from your “char_type” list. As you approach your desired lengths, you can have checks in place to ensure that if a required type does not yet exist in the string, it will be added prior to hitting the desired character length.
Something like this:
import random
character_types = {}
character_types["lower_case"] = list("abcdefghijklmnopqrstuvwxyz")
character_types["upper_case"] = [char.upper() for char in character_types["lower_case"]]
character_types["num"] = [str(i) for i in range(0, 10)]
character_types["s_letters"] = ["_", "#", "."]
character_types["types"] = [key for key in character_types.keys()]
# available_char = lower_case + upper_case + num + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
if not int(user_l) >= 6:
print("invalid number")
length()
return int(user_l)
def password_gen(x):
password = []
password_types = set()
required_types = 4
for i in range(x):
char_type = random.choice(character_types["types"])
if x - len(password) <= 4:
if "s_letters" not in password_types:
char_type = "s_letters"
elif "lower_case" not in password_types:
char_type = "lower_case"
elif "upper_case" not in password_types:
char_type = "upper_case"
elif "num" not in password_types:
char_type = "num"
character = random.choice(character_types[char_type])
password_types.add(char_type)
password.append(character)
set_a = set(password)
# while True:
# valid = True
# if set_a & set(lower_case) == {}:
# password_gen(x)
# valid = False
# if set_a & set(upper_case) == {}:
# password_gen(x)
# valid = False
# if set_a & set(num) == {}:
# password_gen(x)
# valid = False
# if set_a & set(s_letters) == {}:
# password_gen(x)
# valid = False
# if valid:
print("Your password is " + "".join(password))
print(set_a & set(character_types["lower_case"]))
print(set_a & set(character_types["upper_case"]))
print(set_a & set(character_types["num"])) # This was initially not working because num did not consist of strings, whereas the password did.
print(set_a & set(character_types["s_letters"]))
# break
set_password()
There is no need for the final checks because the rules prevent an invalid password from ever being created. This also prevents us from repeatedly generating passwords such that we may find a valid one.
#azro is also correct in mentioning that your length check does not prevent someone from choosing a length less than 6 (fixed above).
There is an improvement you could make to the above code. Currently, when it checks to make sure all required types exist in the password, it is doing so in a fixed order. As such, it will always append the missing character types in the same order (if none of them exist in the string already). You could instead, determine at each step of the way which character types are missing (maintain a list of "missing_types" or something), and then randomly choose a type from a list, and then randomly select a character based on the chosen type.
Your method length does not give assure the number is >=6 because the statement int(user_l) >= 6 doesn't raise an Exception, you may use assert int(user_l) >= 6, but rather than calling the method again and again, use a while loop
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
while not user_l.isdigit() or int(user_l) < 6:
user_l = input("Please enter length of password. Minimum 6.\n")
return int(user_l)
Use a method to build the password, and another one to validate it
def generate_pwd(length):
password = []
for i in range(length):
character = random.choice(available_char)
password.append(str(character))
return password
The {} is empty dict, not empty set, also you can use the boolean value False of an empty set , and use elif to avoid doing all the if is one is fase don't do the next ones
if not set_a & set(ascii_lowercase)
The more readable way would be the other : if all condition are True, the password is valid
valid = set_a & set(ascii_lowercase) and set_a & set(ascii_uppercase) and \
set_a & set(digits) and set_a & set(s_letters)
Here's the full code that uses built-in alphabet from string
import random
from string import ascii_lowercase, ascii_uppercase, digits
s_letters = ["_", "#", "."]
available_char = list(ascii_lowercase) + list(ascii_uppercase) + list(digits) + s_letters
def set_password():
password_gen(length())
def length():
user_l = input("Please enter length of password. Minimum 6.\n")
while not user_l.isdigit() or int(user_l) < 6:
user_l = input("Please enter length of password. Minimum 6.\n")
return int(user_l)
def generate_pwd(length):
return [str(random.choice(available_char)) for i in range(length)]
def password_gen(length):
valid = False
password = []
set_a = set()
while not valid:
password = generate_pwd(length)
set_a = set(password)
valid = set_a & set(ascii_lowercase) and set_a & set(ascii_uppercase) and \
set_a & set(digits) and set_a & set(s_letters)
print("Your password is " + "".join(password))
print(set_a & set(ascii_lowercase))
print(set_a & set(ascii_uppercase))
print(set_a & set(digits))
print(set_a & set(s_letters))

determinating if the input is even or odd numbers

Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description

Categories

Resources