Password checking in Python

Python Methods and Functions | Regular Expressions

Conditions for a valid password:

  1. Must have at least one number.
  2. Must have at least one uppercase and one lowercase letter.
  3. Must have at least one special character.
  4. Must be 6 to 20 characters.
  Input:  Geek12 #  Output:  Password is valid.  Input:  asd123  Output:  Invalid Password !! 

We can check if a given string can be a password or not using several methods.

Method # 1: Naive method (no regular expressions).

# Password check in Python
# using the naive method

 
# Function to check the password

def password_check (passwd):

 

SpecialSym = [ '$' , '@' , ' # ' , '% ' ]

val = True

 

if len (passwd) & lt;  6 :

print ( 'length should be at least 6' )

val = False

 

  if len (passwd) & gt;  20 :

print ( 'length should not be greater than 8' )

val = False

  

if not any (char.isdigit () for char in passwd):

print ( 'Password should have at least one numeral' )

  val = False

 

if not any (char.isupper () for char in passwd):

print ( 'Password should have at least one uppercase letter' )

  val = False

 

if not any (char.islower () for char in passwd):

print ( 'Password should have at least one lowercase letter' )

val = False

  

if not any (char in SpecialSym for char in passwd): 

print ( 'Password should have at least one of the symbols $ @ #' )

val = False

if val:

return val

 
# Main method

def main ():

passwd = 'Geek12 @'

 

  if (password_check (passwd)):

print ( " Password is valid " )

else :

print ( "Invalid Password !!" )

 
Driver code

if __ name__ = = ' __main__' :

main ()

B Output:

 Password is valid 

This code used boolean functions to check if all conditions were met or not. We can see that although the complexity of the code is basic, the length is significant.

Method # 2: Using Regular Expressions

The compile () method of the Regex module creates a Regex object, which allows regex functions on the pat variable. We then check to see if the pattern defined by pat is accompanied by the input string passwd . If so, the search method returns true , which would allow the password to be valid.

# library import

import re

 

def main ():

  passwd = ' Geek12 @ '

reg = "^ (? =. * [az]) (? =. * [AZ]) (? =. * d) (? =. * [@ $!% * #? & amp;]) [A -Za-zd @ $! #% *? & Amp;] {6,20} $ "

  

# writing regular expressions

  pat = re. compile (reg)

 

# regular expression search

mat = re.search (pat, passwd)

 

# check conditions

if mat:

print ( "Password is valid." )

else :

  print ( "Password invalid !!" )

 
Driver code

if __ name__ = = ' __main__' :

main ()

Exit:

 Password is valid. 




Get Solution for free from DataCamp guru