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?
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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