franjapaez
franjapaez

Reputation: 39

Where is my mistake? Checking if password is correct in Python

I am new in Python and programming. I am trying to make a program that verifies that the entered password has a certain format. I was pretty sure my code was correct, but obviously...it's not. It won't exit the while loop when the password is in the correct format. Where is my mistake? Thank you all for your patience!



low = ['abcdefghijklmnopqrstuvwxyz']
up = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
cr = ['@$%&']
digito = ['0123456789']
counter1 = 0
tries = True
while tries:
    length = False
    May = False
    Minus = False
    Num = False
    Char = False
    counter1 += 1
    password = input('Password: ')
    if len(password) > 7 and len(password) < 16:
        length = True
    for caracter in password:
        if caracter in low:
            Minus = True
        if caracter in up:
            May = True
        if caracter in cr:
            Char = True
        if caracter in digito:
            Num = True
    if length and May and Minus and Num and Char:
        print('Password ok.')
        passw = password
        tries = False
    if counter1 == 5:
        print('You had 5 attemps.')
        break

Upvotes: 2

Views: 150

Answers (3)

Yassine
Yassine

Reputation: 21

Each list should contain separate letters instead of an entire string of the alphabet. For example, instead of writing

up = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']

you should write

up = ['A','B','C','D','E','F','G'...] 

A better version of your code might be the following:

tries = True
up = False
low = False
special = False
counter = 0
while tries:
    counter += 1
    
    if counter == 5:
        print('You had 5 attemps.')
        break
        
    password = input("Enter your password: ")
    if len(password) > 7 and len(password) < 16:
        for char in password:
            if char.upper() == char:
                up = True
            if char.lower() == char:
                low = True
            if (ord(char) >= 35 and ord(char) <= 38) or ord(char) == 64:
                special = True
                
        if up and low and special:
                tries = False
                print("Password ok") 
     
    

Upvotes: 1

The issue is that when you check:

"A" in ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']

it returns False. This is because the list ['ABCDEFGHIJKLMNOPQRSTUVWXYZ'] does not contain the element "A". Try to replace the top 4 line with the following code and see if it works:

low = 'abcdefghijklmnopqrstuvwxyz'
up = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cr = '@$%&'
digito = '0123456789'

Upvotes: 5

luk2302
luk2302

Reputation: 57183

low, up, cr and digito should all be strings, not a list with only one string in it: low = 'abcdefghijklmnopqrstuvwxyz'. Otherwise only literally "abcdefghijklmnopqrstuvwxyz" is in low, not "a".

Upvotes: 4

Related Questions