Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of a Password - Python

So I have to create code that validate whether a password:

  • Is at least 8 characters long
  • Contains at least 1 number
  • Contains at least 1 capital letter

Here is the code:

def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper(): 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

like image 674
HaViK Avatar asked Dec 13 '16 09:12

HaViK


1 Answers

You can use re module for regular expressions.

With it your code would look like this:

import re

def validate():
    while True:
        password = raw_input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif re.search('[0-9]',password) is None:
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()
like image 58
zipa Avatar answered Oct 11 '22 03:10

zipa