Hey so I'm a beginner and was just trying out projects to get better so I made a password checker. Just want to see if there is anyway I can make my code neater or more efficient to tips are nice.
import re
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
while True:
pw = input("Enter a string: ")
if 5<=len(pw)<=10:
if (regex.search(pw) == None):
print("Not a valid password, Needs special character")
continue
else:
if any(x.isupper() for x in pw):
print("character has an uppercase letter")
return True
else:
print("Character does not have an upper case")
continue
else:
print("password must be between 5 and 10 characters")
continue
Going to put this into a function and inside main, True returns it's valid
For something as short-lived as this there's little to be gained in terms of runtime efficiency.
However, there are changes you could consider making that will improve the code structure.
First of all, you should write a function that performs the validation - and only that. In that way, no matter where the password is acquired from you can always use the same function.
The string of special characters looks clumsy so put it in a global variable (I conventionally use uppercase variable names to indicate global scope and the fact that its use is constant). Something like this:
SPECIALS = '[@_!#$%^&*()<>?/\\|}{~:]'
def validate(password):
if 5 <= len(password) <= 10: # correct length
if any(sc in password for sc in SPECIALS): # has a special character
if any(c.isupper() for c in password): # has at least one uppercase letter
return True
return False
while True:
password = input('Enter a password: ')
if validate(password):
print('Valid')
break
print('Invalid - try again')