I am trying to loop to ask a password until the user enters a valid password then break out of it. How do I implement this method with a try/except? Is there a better way of doing this? I am a beginning so any help is appreciated!
def is_secure(s):
# This function will check if the passed string s is a valid password
# Return true if string is valid password
# Returns false if string is not a valid password
min_len = 6
max_len = 15
if len(s) < min_len or len(s) > max_len:
return False
else:
return True
while True:
try:
password = str(input("Enter new password:"))
if is_secure(password):
print("Password is secure")
break
except ValueError:
print("False")
else:
print("Password is insecure")
This code should work:
while True:
password = str(input("Enter new password:"))
if is_secure(password):
break
print("Invalid password")
print("Password is secure")
You are trying to handle exceptions that are not thrown anywhere. Another solution would be to throw the exception, instead of printing "invalid password":
raise Exception("Invalid password")
Something like this should hopefully work.
class InsecurePasswordError(Exception):
def __init__(self, message):
super().__init__(message)
class Password:
def __init__(self, pwd: str):
self.pwd = pwd
@property
def pwd(self):
return self._pwd
@pwd.setter
def pwd(self, value):
if len(value) <= 8:
raise InsecurePasswordError('The length of the password is not sufficient!')
elif .....: # Add more conditions
....
else:
self._pwd = value
# And now in your code....
while True:
try:
i = input("Enter new password:")
password = Password(i)
except InsecurePasswordException as e:
print(e)
else:
print("Password is secure")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.