1

我在while下面编写了一个语句来验证姓氏字段并输出一个布尔值以查看是否发生任何错误。程序会将所有错误消息存储在变量中errors。我break在每次错误检查后添加了一条语句,因为我不希望程序在检测到错误后继续检查错误。

我不确定这段代码是否有效 -while在这种情况下是否需要声明?

你怎么看?

valcheck = True

# validate surname
while valcheck == True :

    try :
        surname = str(e2.get())
    except :
        errors += "\nSurname not valid - must be a string."      
        valcheck = False
        break

    # check if surname is not empty
    if len(surname) <= 0 :
        errors += "\nSurname cannot be blank."      
        valcheck = False

    # check if surname is alphabetical
    for i in str(surname) :
        # also, allow for hyphens and apostrophes
        if not(i.isalpha() or i == "'" or i == '-') :
            errors += "\nSurname not valid - must be alphabetical."
            valcheck = False

    # if there are no errors, exit the statement
    break

提前致谢。

4

1 回答 1

0

这看起来更好吗?

try :
    surname = str(e2.get())

    # check if surname is not empty
    if len(surname) <= 0 :
        errors += "\nSurname cannot be blank."      
    else :
        # check if surname is alphabetical
        for i in str(surname) :
            # also, allow for hyphens and apostrophes
            if not(i.isalpha() or i == "'" or i == '-') :
                errors += "\nSurname not valid - must be alphabetical."

except :
    errors += "\nSurname not valid."      
于 2017-02-21T20:35:25.290 回答