Why python code accepts '.' and '-' as numbers?

Question:

Use case:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.

If the function is passed a valid PIN string, return true, else return false.

My code is working for all the randomly generated pins except for:

‘12.0’
‘1234.0’
‘111-‘
‘44444-‘

def validate_pin(pin):
    numbers = '0123456789'
    if len(pin) != 4 and len(pin) != 6:
        return False
    else:
        for i in range(len(pin)):
            if pin[i] in numbers:
                return True
            else:
                break
        return False

Any idea why this would be? These characters do not live within my created variable.

Asked By: MrSandwiches

||

Answers:

As kaya3 suggested, the best way to solve issues like this is to step through with a debugger. You can do this in VS code by hitting "Run and Debug" on the debug tab shown below:

enter image description here

Basically your code is checking if the first character is in numbers or not. If it is a number, the for loop breaks, if it isn’t, the for loop breaks. Here’s a small fix:

def validate_pin(pin):
numbers = '0123456789'
if len(pin) != 4 and len(pin) != 6:
    return False
else:
    for i in range(len(pin)):
        if pin[i] not in numbers:
            return False
        # if pin[i] in numbers:
        #     return True
        # else:
        #     break
    return True
Answered By: Barnaby

Your code is failing on these examples because it is only checking if the length is correct and if the first digit is a number.

This section of your code is where the issue is:

else:
        for i in range(len(pin)):
            if pin[i] in numbers:
                return True

In all of your test cases, i will initially be 0. It will check if pin[0] is in the set of numbers and return True. The return statement breaks you out of the loop and doesn’t check pin[1], pin[2], etc. You need to change your code to check all digits.

Answered By: rnorris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.