def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
#vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters.
if 2 > len(s) > 6:
return False
#All vanity plates must start with at least two letters.
if s[0].isalpha() == False or s[1].isalpha() == False:
return False
#Numbers cannot be used in the middle of a plate; they must come at the end.
#The first number cannot be 0
i = 0
while i < len(s):
if s[i].isalpha() == False:
if s[i] == '0':
return False
else:
break
i = 1
#No periods, spaces, or punctuation marks are allowed.
if s.isalpha() == False or s.isinstance() == False:
return False
#passes all requirements
return True
main()
CodePudding user response:
From the code above I see that you use isinstance() incorrect. Try changing s.isinstance() == False to isinstance(s, type) == False, and choose the type you want to check (int, str.. etc)
Reference: https://www.w3schools.com/python/ref_func_isinstance.asp
CodePudding user response:
The regular expression module provides an easy way to approach what you intend to achieve with the code provided in your question. The code below should do what you intend to achieve, so try it out:
import re # regular expressions module
# All vanity plates must start with at least two letters.
# Numbers cannot be used in the middle of a plate; they must come at the end.
# The first number cannot be 0
rexp = re.compile('^[a-zA-Z]{2,6}([1-9][0-9]*)?')
def main():
plate = input("Plate: ")
# e.g. plate = "plat01"
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
l = len(s)
#vanity plates may contain a maximum of 6 chars (letters or numbers)
# and a minimum of 2 characters.
if 2 > l or l > 6:
return False
if rexp.match(s).span() == (0,l):
return True
return False
main()
P.S. Check out https://regex101.com/r/LNw2pW/1 for detailed explanations of the used regular expression pattern. The 'trick' is to check if the found match length is the same as the length of the input string. If yes, than the input string is valid.