【发布时间】: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