Python check for leading 0 / CS50’s Introduction to Programming with Python

93 Views Asked by At

I recently started with the Python course and got stuck on this problem. The rest of the code should be fine, but I am having difficulty with the for loop. The task is to create a vanity license plate where numbers can only be used at the end and not in the middle. For instance, AAA222 would be an acceptable license plate, but AAA22A would not be acceptable. Also, the first number used cannot be '0'.

Can someone tell me if I'm on the right track or if I need to completely rethink that part of the code?

The goal of the code is to determine if the first numeric character is equal to 0. If yes, it should output False. If the first numeric character is not 0, the loop can be terminated.

Thx in advance!

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    if len(s) < 2 or len(s) > 6:
        return False
    if s[0:2].isalpha() == False:
        return False
    if s.isalnum() == False:
        return False
    if s[1:6].isalpha() == False and s[-1].isalpha() ==True:
        return False
    for i in range(len(s)):
         if s[i].isnumeric() == True:
            if s[i] == "0":
                return False
            else:
                break

    else:
        return True

main()```


1

There are 1 best solutions below

0
R2509 On

Try adding a variable to keep track of whether the loop has found a digit yet (named number_found in the example).

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    number_found = False # keeps track of whether or not a number has been detected yet.
    if len(s) < 2 or len(s) > 6:
        return False
    if s[0:2].isalpha() == False:
        return False
    if s.isalnum() == False:
        return False

    for i in range(len(s)):
        if s[i].isnumeric() == True:
            if number_found == False and s[i] == "0": # if there have not been any numbers yet and a zero is found, i.e. if the first number is zero
                return False
            number_found = True # we found a number!

        if s[i].isalpha() and number_found:
            return False # A letter was found after a number, meaning that the number was is the 'middle' somewhere.

    return True # only reached if it didn't have to `return False` before.

main()

This eliminates the need for the if s[1:6].isalpha() == ... line since it is checked later (in the last part of the loop)