Python检查领先的0 / CS50的Python编程入门

uinbv5nw  于 2023-03-16  发布在  Python
关注(0)|答案(1)|浏览(98)

我最近刚开始学习Python课程,却被这个问题卡住了。其余的代码应该没问题,但我在for循环上遇到了困难。任务是创建一个虚荣的车牌,其中数字只能在末尾使用,而不能在中间使用。例如,AAA 222是一个可以接受的车牌,但AAA 22 A是不可接受的。此外,使用的第一个数字不能是“0”。
有人能告诉我,我是否走在正确的道路上,或者我是否需要完全重新考虑代码的这一部分?
代码的目标是确定第一个数字字符是否等于0。如果是,则输出False。如果第一个数字字符不等于0,则可以终止循环。
提前感谢!

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()```
svdrlsy4

svdrlsy41#

尝试添加一个变量来跟踪循环是否已经找到一个数字(在示例中名为number_found)。

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()

这样就不需要if s[1:6].isalpha() == ...行,因为它是稍后检查的(在循环的最后一部分)

相关问题