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()```
Try adding a variable to keep track of whether the loop has found a digit yet (named
number_foundin the example).This eliminates the need for the
if s[1:6].isalpha() == ...line since it is checked later (in the last part of the loop)