Reputation: 1675
I am creating a password validation module,but I don´t know how can I put certain rules for said password. The password needs at least 1 uppercase letter, 1 lowercase letter and 1 number
Here´s what I have coded so far:
def validacion_contraseña():
flag = 1
import re
while (flag == 1):
cont = 0
pass=input("Ingresa una contraseña:")
# r = re.match("^[a-z]*$", usser)
for x in pass:
cont = cont + 1
if (cont < 8):
print(True)
flag = 0
if not (re.match("[aA-zZ,0-9]",pass)):
print("El nombre de usuario puede contener solo letras y números.")
flag = 0
if (flag == 1):
print(True)
flag = 0
Upvotes: 1
Views: 198
Reputation: 26766
First of all, don't use pass
as a variable - it's a python keyword (which means "do nothing")...
def something():
pass
Next, I'd suggest counting each class (nums/upper/lower) separately and then checking if they meet requirements.
Also note that you almost always want to import
something only once. Except in some advanced cases, all import statements should be at the very top of the file.
Finally, let's use a boolean valid
variable to tidy up the loop condition a bit...
import re
def validacion_contraseña():
valid = False
while not valid:
contrasena = input("Ingresa una contraseña:")
nums = len(re.findall('[0-9]', contrasena))
lower = len(re.findall('[a-z]', contrasena))
upper = len(re.findall('[A-Z]', contrasena))
if nums >= 1 and lower >= 1 and upper >= 1:
valid = True
print('Contraseña: {0}' + contrasena)
We're using re.findall()
to find every non-overlapping match to the pattern. For a 1-character pattern, this effectively returns a list of matching characters.
We then count the number of items returned using len()
.
Upvotes: 2