def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
index = []
for i in s:
if i.isdigit():
index = i
break
print(index)
if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0':
return True
main()
Before I added and index[0] != '0' the code worked perfectly, but for some reason after adding that piece of code, when I go to input "KEVIN" an error(index out of range) pops up. How do I prevent this error from popping while still checking out the requirements for the code in the if statement?
CodePudding user response:
A smaller example shows the problem
def is_valid(s):
index = []
for i in s:
if i.isdigit():
index = i
break
print(index)
if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0':
return True
is_valid("KEVIN")
"KEVIN"
doesn't contain any digits, i.isdigit()
is never True
and the index
list remains empty. Add a check for that case.
def is_valid(s):
index = []
for i in s:
if i.isdigit():
index = i
break
print(index)
if (6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper()
and index and index[0] != '0'):
return True
CodePudding user response:
The code does not consider the edge case for when the string s
has no digits. In that case, index
will be an empty list and index[0] != '0'
will throw an error. Consider adding a condition to check for the length of s
.