Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am currently working on a code that will validate the password on the following basis:

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 uncertain what is wrong in my code, when I enter a password that has a number - it displays that I need a password with a number in it. Any solutions?

1 Answer

0 votes
by (107k points)

There was some issue in your code, it is better to use the 're' module or package when used with 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()



 Want to get certified in Python? Register for this complete Python Training course by Intellipaat.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...