【问题标题】:Surname Validation Code Efficiency - Python姓氏验证代码效率 - Python
【发布时间】:2017-07-11 15:46:25
【问题描述】:

我在下面编写了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

提前致谢。

【问题讨论】:

  • 你最后有一个break,没有continues,所以循环只会执行1次迭代。对我来说,while 声明似乎毫无用处。
  • 为什么你有最后一个break?如果您的程序无论是否发生错误都会退出,为什么不直接使用if 语句?
  • 当我编写代码时,我希望它在找到错误后停止寻找错误,所以我认为while 语句可以使用break 轻松完成此操作。我怎么能使用if 来代替呢?

标签: python python-3.x variables while-loop coding-efficiency


【解决方案1】:

这样看起来更好吗?

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."      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2011-12-28
    • 2021-09-08
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多