I have a password verifier and I have made it that when there is less than 6 digits to change a variable called "invalid" to 1 and if it is is more than 16 digits to change a variable called "invalid" to 1. How do I make it that when the variable is one for it to run the code again and if it is on zero for it to stop. Is there a way to start the code again when the invalid variable is one?
Initialize a variable to check if the conditions are met.
The while loop will run until password is of right size
check = 1
while check == 1:
input = input('Give your password')
if 6 < len(input) < 16:
check = 0
This is how I would do it, after reading your current code:
import re
print("""
Your password needs to have the following:
At least 1 lowercase character
At least 1 uppercase character
1 of these special characters ($##)
Has to have a minium of 6 characters and a maximum of 16 characters
""")
invalid = 1
while invalid:
password = input("Please input a Password: ")
if len(password)<6 or len(password)>16:
print("Password length invalid, please try again")
elif not any(x in password for x in {"$","#","#"}):
print("Password must contain one of these special characters: $##, please try again")
elif not re.search(r"[A-Z]", password) or not re.search(r"[a-z]", password):
print("Password must contain at least one capital and one lower case character, please try again")
else:
print("Password valid")
invalid = 0
Result:
Your password needs to have the following:
At least 1 lowercase character
At least 1 uppercase character
1 of these special characters ($##)
Has to have a minium of 6 characters and a maximum of 16 characters
Please input a Password: hejhejhejhejhejhejhejhej
Password length invalid, please try again
Please input a Password: hej
Password length invalid, please try again
Please input a Password: hejhejhej
Password must contain one of these special characters: $##, please try again
Please input a Password: hejhejhej#
Password must contain at least one capital and one lower case character, please try again
Please input a Password: Hejhejhej#
Password valid
You can add some if-statements. You can use the "break" statement to break out of the loop. Meaning that when "break" is executed the loop will no longer be executed.
I don't know what your code looks like but you could do something like this.
if invalid == 0:
break
invalid = True
while(invalid):
# your code here, accept/recheck password
if not(len(password)<6 or len(password)>16):
invalid = False # passw valid, breaks before next iteration
True and False would seem like better alternatives to 0 and 1 for your application, would still work either way if you choose to use 0 and 1
Related
Im very new to python and I am creating a user login system, I am currently on a bit of creating a username and password with user input that must meet some conditions e.g
username:
Cannot contain any spaces
Must be at least 5 characters
Cannot include special characters
Your system must display a message to the user telling them what they did wrong if they did not meet
one or more of these criteria (so you will need at least 4 error messages).
My code is as below, but surely theress a better way to do this?
while True:
sNewUser1 = input("""Please enter a new username.
The username must NOT contain any spaces, it must have at least 5 characters and
it cannot include any special characters: \n\n""")
if len(sNewUser1) < 5:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
elif sNewUser1.count(" ") > 0:
print("Your username contains one or more spaces, this is not allowed! Please try again! \n")
elif sNewUser1.isalnum() == False:
print("Your username contains a special character please try again! \n")
else:
greetuser()
break
while True:
sNewPass1 = input("""\n\nPlease enter a new password.
It must contain:
At least one Capital letter
At least one lower case letter
At least one special character
It has to be at least 6 characters in length:\n\n""")
if len(sNewPass1) < 6:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
Input prompts can be shortened and more direct.
The whole code should be wrapped in a main() function which is called at the end using the if __name__ == "__main__" condition. This is a convention.
Use is with boolean values, in those conditional statements.
Use the snake_case naming style.
The long strings can be broken into multiple smaller ones.
By now, linters and code-formatters (even Pylint) will not complain about anything.
Your complete code may look something like this, although there is still room for improvement:
"""This is a program for validating usernames and passwords"""
def main():
"""This is the main function"""
while True:
new_user_1 = input("\nPlease enter a new username. "
"It should be at least 5 characters long "
"and not contain spaces or special characters: ")
if len(new_user_1) < 5:
print("Your username is too short. Please try again: ")
elif new_user_1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif new_user_1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
new_pass_1 = input("\nPlease enter a new password. "
"It should be 6 characters long "
"with atleast one uppercase letter, "
"one lowercase letter, and one special character: ")
if len(new_pass_1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in new_pass_1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in new_pass_1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in new_pass_1) is False:
print("\nYour password does not contain digits. "
"Please try again: ")
elif any(not char.isalnum() for char in new_pass_1) is False:
print("\nYour password does not contain special characters. "
"Please try again: ")
elif new_pass_1.replace(" ", "") != new_pass_1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
if __name__ == "__main__":
main()
Edit: The previous answer had some bugs. The new one works as intended:
Strings were broken down into smaller ones, but spaces in the end were ommitted.
Simple for loops were used, which checked whether the whole string was uppercase, lowercase, digits, special characters or not, instead of checking each character in the string. The new code fixes this with the use of a built-in function called any. From Python's official documentation:
any(iterable):
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
Here is an explanation of why/how this works:
elif any(lower.islower() for lower in new_pass_1) means: for any lower in new_pass_1, if lower.islower() returns True, then: code goes here. Therefore, it returns True if any character in the string is lowercase. So if it returns False, it would mean that it did not find any lowercase character in the whole string. The same applies to the checks for uppercase letters and digits.
elif any(not char.isalnum() for char in new_pass_1) means: for any char in new_pass_1, if char.isalnum() does not return True (i.e. the char is a special character), then: code goes here. Therefore, it returns True if any character in the string is a special character (i.e not an uppercase letter, lowercase letter or digit). So if it returns False, it would mean that it did not find any special character in the whole string.
If you're confused about not char.isalnum(): any_string.isalnum() checks whether any_string is alphanumeric or not, i.e whether it is made up of alphabets and numbers only. So inverting it with not char.isalnum() would now check whether any_string is not alphanumeric. And we know that if something is not alphanumeric, it is a special character. Note that this will consider whitespaces to be special characters as well, so I've added a final if statement to check for whitespaces.
I'm trying to write a program in Python where the user enters an answer and if it's less than 5 characters or has a special character like !, #, #, $, it's supposed to get kicked and the user tries again.
It's okay if something like ),(,*,&,^ gets entered, I just can't have !,#,#,$.
I was wondering if someone could explain it for me better than what my poor Googling found.
Thanks
Here's my code:
while True:
print("Without entering any special characters !, #, #, $")
answer = input("Please enter an answer >= 5 characters: ")
if len(answer) >= 5:
print("Your answer was greater than or equal to 5 characters!")
print("Success!")
break
else:
print("Please read directions and try again.")
You can use any to figure out if any character in your answer is in ['!','#','#','$'].
if len(answer) >= 5 and not any(i in ['!','#','#','$'] for i in answer):
Like this:
word='yaywords#'
badchars='!##$'
if len(list(set(list(badchars)) & set(list(word)))) == 0:
'yay it worked'
You can take the intersection of the set of characters in the answer with the set bad characters to see if any bad characters are in the answer:
if len(answer) >= 5 and not set(answer) & set('!##$'):
I have been trying to make my own, very simple program to check if the text string the user has copied can be considered a strong password, based on the regular exressions. In the program, I wanted a strong password to be considered to have at least 8 characters, at least one lower and one upper case character, and also at least one digit.
The code I wrote looks like this:
import re, pyperclip
# regex for password
regexEight = re.compile(r"\w{8,100}") # regex for 8 char.
regexLower = re.compile(r'[a-z]') # regex for lower.
regexUpper = re.compile(r"[A-Z]") # regex for upper.
regexNum = re.compile(r"\d") # regex for number.
# get text from paste
text = str(pyperclip.paste())
# see if text matches every regex.
mo = regexEight.search(text)
if mo != None:
exit
else:
print("Password to short.")
mo2 = regexLower.search(text)
if mo2 != None:
exit
else:
print("Password need to contain at least one lower case character.")
mo3 = regexUpper.search(text)
if mo3 != None:
exit
else:
print("Password need to contain at least on upper case character.")
mo4 = regexNum.search(text)
if mo4 != None:
exit
else:
print("Password need to contain at least one digit.")
# return this if every regex matches.
if mo or mo2 or mo3 or mo4 != None:
print("You have a strong password.")
I'm a complete beginner at RE so I used None to see if the object was matching or not (if it matched it returned the particular password, if it didn't mo(1,2,3) = None). However, I kind of feel that this way is quite unusual, or at least I don't think that is how RE should be handled, so that is why I asked here.
Is there any way to make this code simpler? Or is this way quite OK for a program? In my opinion it feels like the code would be better without all the if's and the None's. Is there a way to get rid of them?
I think a decent general approach would be to create some structure which holds the regexes that you want to check and the corresponding error messages.
import re
tests = [
(re.compile(r"\w{8,100}"), "Too short."),
(re.compile(r"[a-z]"), "Add lowercase letter."),
(re.compile(r"[A-Z]"), "Add uppercase letter."),
(re.compile(r"\d"), "Add number.")
]
check = True
for regex, message in tests:
if regex.search("example_password") is None:
print(message)
check = False
if check:
print("Strong password.")
You're making this way more complex than it needs to be:
def validate_password(password):
if not password or len(password) < 8:
print("Password too short!")
elif password == password.lower() or password == password.upper():
print("Password must contain at least one lowercase and one uppercase character!")
elif not any(c.isdigit() for c in password):
print("Password must contain at least one digit!")
else:
return True # all is well
return False # didn't validate
This question already has answers here:
can this code be shortened or improved? [closed]
(3 answers)
Closed 9 years ago.
I am writing a program that is supposed to take a string (the password entered by user) and test it to make sure it meets the following requirements:
must contain at least one uppercase letter and one lowercase letter
must start with a letter
minimum of eight characters
no blanks
must contain at least two digits
this is what i have so far and I'm stuck getting invalid syntax errors
running = True
while running:
valid = 0
password = str("Enter Password: ")
if len(p) <8:
print ("The password you entered is too short. Please try again.")
running = False
import re
#check if contains a digit
if re.search(r '\d', password):
password = valid
#check if contains uppercase letter
if re.search(r '[A-Z]', password):
password = valid
#check if contains lowercase letter
if re.search(r '[a-z]', password):
password = valid
#check if contains only letters
if re.search(r "[a-z]", password) and re.search(r "[A-Z]", password):
print ("Password must contain at least 2 digits. Please try again.")
#check if contains all lowercase letters
if password.islower():
print ("Password must contain at least 1 uppercase letter. Please try again.")
#check if contains all uppercase letters
if password.isupper():
print ("Password must contain at least 1 lowercase letter. Please try again.")
if password == valid:
print ("Valid Password")
There are multiple problems with the code shown, in addition to the spacing error in your regexps, as mentioned by DevEight.
1) password = str("Enter Password: ") - this does not ask the user for a password, this sets the name password to refer to the string "Enter Password: ". You want input instead (or raw_input for Python version 2.x).
2) if len(p) <8: - p is not a defined name. Presumably you mean password.
3) running = False - this is the only place you set this variable, but it controls your while loop. Your loop only exits when this is false, so this will keep looping until the password is too short, whereup it will eventually exit.
4) password = valid - this sets the password name to refer to the contents of the variable valid, which you initialize to 0. You then run further regular expression searches against the integer 0, which are of course wrong.
5) if re.search(r "[a-z]", password) and re.search(r "[A-Z]", password): - this is commented to say that it requries that there be at least two numbers in the password. It doesn't. I have no idea why you might think it does.
6) if password == valid: - this kind of sort of works, in the sense that you may have previously set password to have the same value as valid. As mentioned above, that's wrong, but it means this could sometimes return True. With working code, you need completely different logic.
7) To top it all off, your question refers to syntax errors from running = True - but that assignment isn't present anywhere in the code.
On the up side, good use of isupper and islower. Those methods make your earlier upper and lowercase regexp searches unnecessary.
You don't seem to get the password from the user.
password = str("Enter the password")
should be:
password = raw_input("Enter the password")
Then, you are checking for valid conditions, which may cause logical errors. So, instead of checking if it satisfies all conditions, check if it does not satisfy any condition (ie) reverse of what you are doing right now..
Eg)
flag = 1
invalid = 0
if(len(password)<8):
flag = 0
if password.islower():
flag = 0
#all conditions
#at last, check for the flag value.
if flag:
print "Password valid"
else:
print "Password not valid"
I am trying to create a little program in which the user enters a password into the console. The program then checks whether the password is weak, medium or strong depending what the user has typed in.
I need to check how many uppercase, lowercase and numbers have been entered and then tell the user how strong their password is.
I have most of the program completed, but since I haven't really used Python for long I am not too familiar with anything advanced, bear in mind younger people have to understand this code too who are not going to be good at coding themselves.
So far I have:
#Welcome the user to the application.
print("Hello, please enter a password to check how secure it is");
#Set a variable called MinPass and set a value of 6.
MinPass = 6;
#Set a variable called MaxPass and set a value of 12.
MaxPass = 12;
#Set variable EnteredPass and wait for user input
EnteredPass = input("Password: ");
while len(EnteredPass) < MinPass:
print("Your password is too short, please enter a longer password and try again")
EnteredPass = input("Password: ");
while len(EnteredPass) > MaxPass:
print("Your password is too long, please shorten it and try again!");
EnteredPass = input("Password: ");
Please note, this is for educational purposes only. I'm not planning on making a program in an intent to steal random password. It's for a part of a course that's going on in my school!
This contains a few more-advanced concepts, but should be easy enough to follow:
import string
def long_enough(pw):
'Password must be at least 6 characters'
return len(pw) >= 6
def short_enough(pw):
'Password cannot be more than 12 characters'
return len(pw) <= 12
def has_lowercase(pw):
'Password must contain a lowercase letter'
return len(set(string.ascii_lowercase).intersection(pw)) > 0
def has_uppercase(pw):
'Password must contain an uppercase letter'
return len(set(string.ascii_uppercase).intersection(pw)) > 0
def has_numeric(pw):
'Password must contain a digit'
return len(set(string.digits).intersection(pw)) > 0
def has_special(pw):
'Password must contain a special character'
return len(set(string.punctuation).intersection(pw)) > 0
def test_password(pw, tests=[long_enough, short_enough, has_lowercase, has_uppercase, has_numeric, has_special]):
for test in tests:
if not test(pw):
print(test.__doc__)
return False
return True
def main():
pw = input('Please enter a test password:')
if test_password(pw):
print('That is a good password!')
if __name__=="__main__":
main()
You can use the following functions:-
isalnum() # To check for alpha numeric characters
isalpha() # To check for the presence of only alphabets
for eg.
password = input("Enter the password: ")
if password.isalnum() == False:
print "Password should contain atleast one special character or number"
if password.isalpha() == False:
print "Password should contains atleast some alphabets."
To check for the presence of capital or small letters you can use this:-
temp = passsword.lower()
if temp == password:
print "Password should contain atleast one capital letters"
How it Works?
Although this code is self-explanatory, there is nothing rocket-science about it, I will explain it since, you seem to be a beginner to me:-
str.isalnum() returns False if the string contains some non alphabet characters
str.isalpha() returns false if the string does not contain a single alphabet
By creating
temp
I am storing a copy of the password which is lowercase. So if the password variable contains some capital letters then the
temp == password
will return False, and you can find out whether the string contains some capital letters or not.
As pointed out by #MartijnPieters, you can use
if not password.isalnum():
also instead of
if password.isalnum() == False:
Although, the first way is more "pythonic"
Write MATLAB code to check for the strength of an entered password, the code should output: ‘weak’, ‘medium’, ‘strong’, and very strong’ depending on the length of the password, the use of both capital and small letters, the use of numbers and special character.