Home > Software design >  Why is my code accepting '.' and '-' as numbers?
Why is my code accepting '.' and '-' as numbers?

Time:11-11

I am new to Python, and I am trying to complete the following training problem:

=========

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.

I know there would be easier ways to do this same function. I would love to hear some of these, but also would love to learn why my current one does not work.

Thanks!

CodePudding user response:

As 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

CodePudding user response:

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.

CodePudding user response:

Good answers already - you break after the first character so other nonconforming ones are ignored. You could tighten up your code with

numbers = '0123456789'

def validate_pin(pin):
    return len(pin) in (4, 6) and all(n in numbers for n in pin)
  • Related