I am trying to create a user login system program. I am trying to make sure the password must have at least 10 characters which I have done, but I'm having trouble making sure it has at least two numbers and only underscore as a special character. I have seen some solutions about numbers and I don't get them and they rarely have at least 2 digits.
Here is my code:
print("Welcome ")
print('')
print('New users should enter Sign to create an account')
print('')
print('')
username = input('Enter your Username: ')
if username == 'Sign':
while True:
usernames = ['Dave','Alice','Chloe']#A list that stores usernames
create_user = input('Enter your new username: ')
if create_user in usernames:
print('This user name has been taken .Try again')
continue
else:
break
usernames.append([create_user])
while True:
create_pass = input('Enter your your user password: ')
passwords = []#A list thst stores password
pass_len = len(create_pass)
if pass_len < 10:
print('Your password must be at least 10. Try again')
continue
else:
print('')
print('You are now a verified user.')
print('Run the application again to re-login.')
print('Thank You')
break
else:
password = input('Enter your password')
print('Visit www.bitly/p8?. to continue')
If you're not wanting to use regex, you could add some simple logic like this:
num_count = 0
for character in create_pass:
if character.isdigit():
num_count += 1
if num_count < 2:
print('You must have at least 2 numbers in your password')
This is how I'd do it. You can check for the underscore with in and use regex to search for the numbers.
import re
test = 'hisod2f_1'
underscore = '_' in test
twonums = len(re.findall(r'\d', test)) >= 2
if underscore and twonums:
# your logic
Related
so i am new to python and trying to create a simple login system which registers users and login but i am having trouble in password and username validation following is the code (note that i have divided my code in different modules because i am thinking of implementing it in future:
register module
import re
def register():
with open('username.txt', mode='a')as user_file:
username = input('Enter Username : ')
user_file.write(f"{username}\n")
with open('password.txt', mode='a')as pass_file:
password = input('Enter Password: ')
pattern= re.compile(r'[a-zA-Z0-9##!$%^&*]{8,}')
if password==pattern.fullmatch(password):
pass_file.write(f'{password}\n')
else:
print("your password should be atleast 8 characters long!")
login module
def login() :
l_user = input('Username: ')
l_pass = input('Password: ')
with open('username.txt', mode='r')as user_file:
for users in user_file:
validate_u = user_file.readlines()
with open('password.txt', mode='r')as pass_file:
for passwords in pass_file:
validate_p = pass_file.readlines()
if l_user==validate_u and l_pass==validate_p:
print('hello')
else:
print('login failed')
finally main module
import Enigma_Register
import Enigma_login
print('1-Login\n2-Register')
choice = int(input("enter choice: "))
if choice == 1:
Enigma_login.login()
elif choice == 2:
Enigma_Register.register()
Enigma_login.login()
else:
print('Invalid Choice!')
For your login function, replace the last four lines with:
if l_user+"\n" in validate_u: #ReadLines() adds newlines
user_num = validate_u.index(l_user+"\n")
if l_pass+"\n" == validate_p[user_num]:
print("Password correct!")
else:
print("Password incorrect!")
else:
print("Cannot find your username!")
also, the for users in user_file and for passwords in pass_file are unnecessary: just put the readlines() method on its own, without a loop.
Additionally, replace the if password==pattern.fullmatch with if pattern.match(password).
I'd also suggest moving the file writes until after you've validated the password, otherwise "ghost usernames" with no passwords could appear, easily causing problems; or you could replace all of the code in your register() function after password = input("Enter password: ") with
pattern = re.compile( [YOUR REGEX HERE] )
while not pattern.match(password):
print("Your password is invalid.")
pass_file.write(f'{password}\n')
user_file.write(f'{username}\n')
The idea is that you enter any passwords/characters and then it tries to find that word that you have entered by trying out different combinations of letters and numbers (it really is pointless huh)
The problem right now is that "pw_guess" only prints out one letter or number at a time. There also appears to be duplicates. For example i found that letter "e" was printed 6 times, though should only print it once.
import random
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
pw = input("Enter a password: \n")
pw_lenght = len(pw)
while True:
for i in range(pw_lenght):
random_character = random.randrange(len(characters))
pw_guess = characters[random_character]
if pw_guess == pw:
print('Password found!\nPassword: ', pw)
exit()
print(pw_guess)
It is suppose to print and try out as many letter/numbers at a time as how many have been entered in to the user input.
For example:
You type "password123" to the input. Then it will count how many
characters there are in that user input (11 in this example), and
starts trying out and printing different combinations of characters.
One print should now include 11 random characters. Then at some point
it will get right combination and stop.
As said above, now it only prints one character at a time and there are also duplicate characters which i don't want.
I've tried putting just one letter to the user input, and it guessed it right, so otherwise it works fine.
import random
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
pw = input("Enter a password: \n")
pw_lenght = len(pw)
while True:
for i in range(pw_lenght):
random_character = random.randrange(len(characters))
pw_guess = ''.join([characters[random.randrange(len(characters))] for x in range(len(pw))])
if pw_guess == pw:
print('Password found!\nPassword: ', pw)
exit()
print(pw_guess)
Your inner loop should assemble all the random characters into a single password guess, instead of guessing each letter separately.
import random
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
pw = input("Enter a password: \n")
while True:
pw_guess = ''
for i in range(len(pw)):
pw_guess += random.choice(characters)
if pw_guess == pw:
print('Password found!\nPassword: ', pw)
break
print('Password not found. Incorrect guess: ', pw_guess)
Since Python 3.6 you can use random.choises to get more characters at once.
I would recommend the string-module for better readability.
It's very annoying to fill the terminal with thousands of incorrect guesses, so I've changed the code a little.
import string
import random
characters = string.digits + string.ascii_letters
password = input('Enter a password:\n')
guesses = 1
while True:
pw_guess = ''.join(random.choices(characters, k=len(password)))
if password == pw_guess:
break
guesses += 1
print('Password found!')
print(f'Password: {pw_guess}')
print(f'{guesses} guesses needed')
I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break
I have set up a program to change a "password". I have it checking to see if it is at least 8 characters, contains a capital letter and has a number, and if it does not meet this criteria, it asks for the password again. I have everything working except the checking for a number and I was wondering if someone could help.
npwv = 1
while npwv == 1:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if npwc.isupper()== False:
if npwc.islower()== False:
if len(npwc) >= 8:
if str.isdigit(npwc) == True:
npw=npwc
print("Your password has been changed")
else:
print("Your password must contain a number")
npwv = 1
else:
print("Your password must contain at least 8 characters.")
npwv = 1
else:
print("Your password must contain at least 1 upper case character.")
npwv = 1
else:
print ("Passwords don't match")
npwv = 1
You are checking if the password itself is fully uppercase or composed of numbers. What you need to check if if the characters in the password match this criteria.
has_upper = any([c.isupper() for c in npwc])
has_digit = any([c.isdigit() for c in npwc])
You can also use regular expressions.
By the way, you should prefer getpass to get the password from the user.
Have you considered using .isalnum()?
>>> foo = "123asd"
>>> foo
'123asd'
>>> foo.isalnum()
True
>>>
Edit: Judging by the other answers, I am not sure what are you looking for, could explain it with examples?
I would suggest using sets, and the string package from stdlib for your list of acceptable characters.
I would also suggest refactoring a bit to remove a lot of the nesting with if / else branches.
import string
upper = set(list(string.uppercase))
lower = set(list(string.lowercase))
numbers = set(list(string.digits))
while True:
npw = input("Please enter new password: ")
npwc = input("Please confirm new password: ")
if npwc != npw:
print("Passwords don't match")
continue
if len(npcw) < 8:
print("Your password must contain at least 8 characters.")
continue
chars = set(list(npwc))
if not upper.intersection(chars):
print("Your password must contain at least 1 upper case character.")
continue
if not lower.intersection(chars):
print("Your password must contain at least 1 lower case character.")
continue
if not numbers.intersection(chars):
print("Your password must contain a number")
continue
npw = npwc
print("Your password has been changed")
break
This can be made more compact but yeah..
while True:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if any(x.isupper() for x in npwc):
if any(x.islower() for x in npwc):
if len(npwc) >= 8:
if any (x.isdigit() for x in npwc):
npw=npwc
print("Your password has been changed")
#break # you probably want to exit the loop at this point
else:
print("Your password must contain a number")
else:
print("Your password must contain at least 8 characters.")
else:
print("Your password must contain at least 1 upper case character.")
else:
print("Your password must contain at least 1 lower case character.")
else:
print("Passwords don't match")
This looks like a job for regular expressions. Solution below:
import re
def password_validator(password):
if len(password) < 8:
return False, "Your password must contain at least 8 characters"
if not re.match('.*[0-9]', password):
return False, "Your password must contain a number"
if not re.match('.*[A-Z]', password):
return False, "Your password must contain at least 1 upper case character."
if not re.match('.*[a-z]', password):
return False, "Your password must contain at least 1 lower case character."
return True, "Your password has been changed"
while True:
npw = input("Please enter new password.")
npwc = input("Please confirm new password")
if npw != npwc:
print("Passwords don't match")
continue
is_valid, message = password_validator(npw)
print(message)
if is_valid:
break
You could also validate the whole thing in one go as:
pattern = """
(?=.*[a-z]) # use positive lookahead to see if at least one lower case letter exists
(?=.*[A-Z]) # use positive lookahead to see if at least one upper case letter exists
(?=.*\d) # use positive lookahead to see if at least one digit exists
[A-Za-z0-9##$%^&+=]{8,} # match any character in [] at least 8 times
"""
pwd_validator = re.compile(pattern, re.VERBOSE)
if pwd_validator.match(password):
# legit password
else:
# no match ask again
Hope this helps. The re.VERBOSE just makes this regular expression self-documenting so a lot easier to understand in future.
Function check whether user's password qualifies, as far as alphanumeric characters, 10 characters length min, and lower and uppercase characters.
def is_good_password(password):
count_upper, count_lower = 0, 0
for characters in password:
if characters.isupper():
count_upper += 1
if characters.islower():
count_lower += 1
is_password_good = True
if len(password) <= 10:
print "Password Is Too Weak, Must Be More Than 10 Characters Long!"
is_password_good = False
if set(database).intersection(password):
print "Password Must Contain Alphanumeric Characters!"
is_password_good = False
if count_upper < 1 or count_lower < 1:
print "Password Must Contain at Least One Uppercase and One Lowercase Character!"
is_password_good = False
create_user(database)
print "Welcome! Username & Password Successfully Created!"
return is_password_good
I want the create_user() function raw_input for passcode to return back to passcode if the user's password doesn't qualify on the above function; however, the create_user() function returns the passcode raw_input back to the user raw_input if the password doesn't work.
How can I fix this?
Thanks
def create_user(database):
good_user = False
good_pass = False
while not good_user or not good_pass:
user = raw_input("Enter a New Username: ")
good_user = is_good_user(user)
passcode = raw_input("Enter a New Password: ")
good_pass = is_good_password(passcode)
database[user] = passcode
dump_data()
Just add another loop; you don't need to use flag variables either, just use break to end the loop when you have a good user or password:
while True:
user = raw_input("Enter a New Username: ")
if is_good_user(user):
break
print "That's not a good username, please try again"
while True:
passcode = raw_input("Enter a New Password: ")
if is_good_password(passcode):
break
print "That's not a good password, please try again"
database[user] = passcode
dump_data()
Did I understand you correctly?
def create_user(database):
good_user = False
good_pass = False
while not good_user:
user = raw_input("Enter a New Username: ")
good_user = is_good_user(user)
while not good_pass:
passcode = raw_input("Enter a New Password: ")
good_pass = is_good_password(passcode)
database[user] = passcode
dump_data()