Repetitive Password code - python

I am trying to create a password generator. I have succeeded in creating a functional code but it keeps on showing how it generates the passwords instead of just giving three lines as shown:
This is my code:
def Generate(): #menu function, Generates a password
global password
print("Generating...")
chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!##$%^&*()?" #These are the avaliable characters available to the password
length = input("password length?") #asks for how long the user wants their password
if int(length) < 25: #Doesn't allow the code to print over 26 characters
length = int(length)
for p in range(3):
password = " "
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password
print(password)
else:
print ("The password can only be between 8-24 characterss long")
Generate ()
This is my program running:
Generating...
password length?14
*
*C
*CD
*CDb
*CDbF
*CDbFA
*CDbFAi
*CDbFAiK
*CDbFAiKk
*CDbFAiKkA
*CDbFAiKkAa
*CDbFAiKkAa9
*CDbFAiKkAa9m
*CDbFAiKkAa9mr
7
7Y
7Ys
7Ysy
7Ysyj
7Ysyjj
7Ysyjj2
7Ysyjj28
7Ysyjj28C
7Ysyjj28Ch
7Ysyjj28Chq
7Ysyjj28Chqk
7Ysyjj28Chqk(
7Ysyjj28Chqk(k
E
E%
E%C
E%C8
E%C8(
E%C8(w
E%C8(w7
E%C8(w7M
E%C8(w7Mj
E%C8(w7MjP
E%C8(w7MjPO
E%C8(w7MjPOz
E%C8(w7MjPOzx
E%C8(w7MjPOzxx
Could you please help me to make the code just output three words?
Much appreciated.

You have indented this incorrectly:
for p in range(3):
password = " "
for c in range(length):#for loop which
password += random.choice(chars)#randomly choses characters at random to create the password
print(password)
It should be this:
for p in range(3):
password = " "
for c in range(length):#for loop which
password += random.choice(chars)#randomly choses characters at random to create the password
print(password)
By placing the print statement in the first loop, it will only execute at the end of each iteration of p, rather than each iteration of c.

There is so much things we could help you out here than just what you asked for actually! I'll write same code with your requirements ( assuming I got them all right ) with comments.
import random
def generate_password(): #menu function, Generates a password
# global password # NOT NEEDED BUT I"M ASSUMING THINGS HERE
print("Generating...")
chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!##$%^&*()?"#These are the avaliable characters available to the password
length = int(input("password length?")) #asks for how long the user wants their password
if length <= 26: #Doesn't allow the code to print over 26 characters -> THIS SHOULD BE LESS THAN OR EQUAL TO 26 BC YOU SAID OVER 26 CHARS
for p in range(3):
password = " " # EMPTY STRING.. PYTHON WOULDN'T MIND
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password -> CONCATENATION HERE.. WE LOVE IT.
print(password) # THIS WAS OUT OF PLACE.
else:
print ("The password can only be between 8-24 characterss long")
generate_password () # PERFECT!
generate_password()
Now after I come with somewhat ok-ish code I can't sleep at night bc I know I can improve it even more if I do it in my way.
import random
import string
def generate_password(): #menu function, Generates a password
print("Generating...")
try:
length = int(input("password length?")) #asks for how long the user wants their password
if 8 <= length < 25: # Doesn't allow the code to print over 26 characters -> THIS SHOULD BE LESS THAN OR EQUAL TO 26 BC YOU SAID OVER 26 CHARS
password = ''.join(random.choice(string.ascii_letters + string.digits + "!##$%^&*()?") for _ in range(length)) # throw away variable caution here!
print(password)
else:
print("The password can only be between 8-24 characterss long")
generate_password() # PERFECT!
except Exception as e: # Do some homework on what kind of exception(s) you would like to catch ( like ValueError)
print(e)
pass # Don't just pass it. Do something here depending on the Exception
generate_password()

The print statement in your inner loop for the character selection, is the culprit here, just push it one indentation to the left and it should work.
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password
print(password)
just keep it in the for p in range(3): loop.

Sure, just move print out of loop:
for c in range(length):
password += random.choice(chars)
print(password)
Also you could consider this:
password = ''.join([random.choise(chars) for _ in range(length)])

Related

how to make the user choose between options

I make password genrator using python then the teacher told to create a code that make the user choose what he want in the password
the password contains
1- lower case characters
2- upper case characters
3- numbers
4- punticuation marks
the teacher want me to make the user choose if he want punticution or not
if he dont want it have to be deleted from the password
i tried so hard but i got stuck
from msilib import change_sequence
import string
import random # I import this line to make the password unorgnaized
# this code below is all the characters we need for the password
s1 = list(string.ascii_lowercase)
s2 = list(string.ascii_uppercase)
s3 = list(string.digits)
s4 = list(string.punctuation)
# this code is for the user to put how much characters he need
characters_number = input("how many characters for the password?:")
# this while loop code is to make the user choose only 6 characters and up
while True:
try:
characters_number = int(characters_number)
if characters_number < 6 :
print("you need at least 6 characters") # if the user choose an letter or digits it will not allow him
characters_number = input("please enter the number again:")
else:
break # I break the loop here if the user write the correct data
except: #this code here if the user enter anything except numbers
print("please enter numbers only")
characters_number = input("how many characters for the password?:")
# the random and shuffle is to make the password unorgnized
random.shuffle(s1)
random.shuffle(s2)
random.shuffle(s3)
random.shuffle(s4)
# the password that will appear to the user it contains upper and lower letters, numbers and digit
# part1 here is for the letters I allocated 30% of the password for letters
# part2 here is for the digits and numbers I allocated 20% of the password for letters
part1 = round(characters_number * (30/100))
part2 = round(characters_number * (20/100))
password = []
for x in range(part1):
password.append(s1[x])
password.append(s2[x])
#the for loops here here is to create the password
for x in range(part2):
password.append(s3[x])
password.append(s4[x])
#this code here is to transform the password for list method to a string
password = "".join(password[0:])
print(password)
You can write a function like this:
def isUserNeedPunctuationMarks():
result = None
while True:
inp = input("Do you need punctuation marks in your password? (y/n)")
inp = inp.lower()
if inp == "y":
result = True
break
elif inp == "n":
result == False
break
else:
print("You must enter y or n")
return result
The above function will return True if the user needs punctuation marks, and False otherwise. User has to type y (for yes) or n(for no).
You can call isUserNeedPunctuationMarks() in the right place in your code. For example, removing punctuation marks from password string, you have to write a condition like this:
import re
if not isUserNeedPunctuationMarks():
password = re.sub(r'[^\w\s]', '', password) # This removes punctuation marks from a string using regex
Hope this helps :)

I am trying to print each alphabet beside eachother in a for loop in python. Please help me

Ok so I am making a password maker in python and I am trying to create a secure password that shows up in the console like this:
Fdm6:yguiI
I also want the user to specify the number of alphabets the password will need (which actually works)
anyway, here is the code
import random
options = '1234567890!##$%^&*()`~-_=+\|]}[{\'";:/?.>,<QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
char_list = tuple(options)
print("""Password checker
This either checks your password or creates a sequre password.
Your commands are \"create password\" and \"check password\"""")
command = str(input('Type your command: '))
if command.lower() == 'create password':
digit_count = int(input('How many digits do you want your password to be? (Must be more than five and under 35): '))
if digit_count >= 5 and digit_count <= 35:
for i in range(digit_count):
password = random.choice(char_list)
print(password)
else:
print('Bruh I told you to give more than 5 or under 35')
Right now, the output is like this
Someone please help mee
Replace this part
for i in range(digit_count):
password = random.choice(char_list)
print(password)
with:
password = ''.join(random.choices(char_list, k=digit_count))
print(password)
Add an end parameter to your output print statement -
for i in range(digit_count):
password = random.choice(char_list)
print(password,end='')
By default, the end is equal to '\n'. So it changes the line if you do not specify the end as '' (empty)
If you do want to store the password, then use a list comprehension -
p = [random.choice(char_list) for i in range(digit_count)]
password = ''.join(p) # Or, you could just write this into a single line
print(password)

Password generator generates the same passwords

I'm trying to make a password generator in Python but I have some problems with it.
My code is down below:
import random
import time
f = open("password_list.txt", "a+")
start = time.time()
password = ""
chars= "123456789"
number = int(input("Number of passwords to generate? = "))
length = int(input("Password length? = "))
for p in range(number):
password = ""
for c in range(length):
password += random.choice(chars)
print(password)
f.write(password + "\n")
print('time: ' + str((time.time() - start)) + ' sec')
f.close()
Everything works fine but the only problem is sometimes it generates the same passwords in the text file. How can I avoid that?
One way to avoid the duplication issue is to put the passwords into a set in your loop, and keep looping until the length of the set is the number of passwords you want to generate. Then you can write the contents of the set to the file. This shows how to generate the set of passwords:
import random
chars= "123456789"
number = 5
length = 8
passwords = set()
while len(passwords) < number:
password = ""
for c in range(length):
password += random.choice(chars)
passwords.add(password)
print(passwords)
Sample output:
{'67824479', '67159221', '78423732', '77922952', '83499619'}

How to single out a number and special character at the end of the password

Write a program that asks the user to enter a password (with the prompt "Password:"). It should then reward the user with "Congratulations, you're in!" if the password is between 8 and 20 characters long (inclusive), ends with a digit, and contains a period or comma. Otherwise, it should say "Wrong! This incident will be reported!"
I need to be able to have a number at the end and contain either a period or a comma. I am not sure on how to isolate these two parts of the password. What do I do to have the user asked to enter a password?
user_pass = str(input())
if (len(user_pass <= 8) and (len(user_pass >= 20)) and
print ("Congratulations, you're in!")
else:
print ('Wrong! This incident will be reported!')
Just add more conditions using and.
Python 3:
password = input("Password: ")
if (8 <= len(password) <= 20) and password[-1].isdecimal() and any(x in password for x in {'.', ','}):
print("Congratulations, you're in!")
else:
print("Wrong! This incident will be reported!")
Python 2:
password = raw_input("Password: ")
if (8 <= len(password) <= 20) and unicode(password[-1]).isdecimal() and any(x in password for x in {'.', ','}):
print("Congratulations, you're in!")
else:
print("Wrong! This incident will be reported!")
A hint:
def password_is_good(password):
return (
password_length_is_correct(password) and
password_ends_with_digit(password) and
password_contains_punctuation(password)
)
def password_length_is_correct(password):
# implement this, and the rest.
password = str(input())
if password_is_good(password):
# do something.
else:
# do something else.
You can access string elements by index, with negative indexes counting from the end; e.g. password[-1] would access the last character.
You can use the in operator to check for a character to be present in a string, like if 'c' in 'abcdef'.

calling functions for a password checker

this is my password checker code (whether it is valid or not)
I need to run the password checker for 5 times, until it's valid.
If it's valid, I have to break out of the loop.
The password should be more than 7 characters.
The password needs to include both numbers (at least two) and characters.
(If not, return False)
There should be no space.
If there is anything else than numbers and characters, I need to return False
I need to run my password_checker function in the for loop,
but I'm not so sure what to say after 'if'.
I have tried -
if a=False:
print(password_checker(i))
print(Invalid password)
but it didn't work.
Also, I don't understand how should I call my password_checker() in the for loop.
Finally, I need to put a break in my for loop
if the password in the input is valid.
But I'm not sure where is the appropriate part to place it
def password_checker(password):
a=True
num_Count = 0
if password.isalpha() == True:
print ("error! needs numbers")
a = False
if password.isnum() == True:
print ("error! needs characters")
a = False
if password.isspace() == True:
print ("error! no space allowed")
a = False
if len(password)<=8:
print ("error! needs more than 8 characters")
a = False
for i in range(0, 10):
num_Count += password.count(i)
if num_Count(password.count()) < 2:
print("error! needs at least 2 numbers")
a = False
password = str(input("Enter password: "))
for i in range(0,5):
if ____________________:
print(password_checker(i))
print("Invalid password")
else:
print(password_checker(i))
print("Valid password")
break
How should I correct my code in order to make my function work?
for i in range(0,5):
password = str(input("Enter password: "))
password_checker_result = password_checker(password)
if not password_checker_result:
print("Invalid password")
else:
print("Valid password")
break
This code will work for you, now let me explain:
The flow is as following:
This is done 5 times (is inside the for loop):
1) Request password from user.
2) Check if password is valid.
3) Print according to valid/not valid result.
The fact that you are using a for loop does not require you to actually use the iteration index (meaning 'i' in our case)

Categories

Resources