在Python 3脚本中,我有一个部分,我有一个for循环,我想做的东西,然后进行验证检查。如果它没有通过验证检查,我想跳过处理循环的其余部分,然后继续循环中的下一个项目。如果它通过了验证检查,我希望脚本执行更多的操作,然后执行另一个验证检查,其中它与第一次验证检查相同;如果它没有通过验证,则跳过for循环中的其余代码并继续循环的下一次迭代;如果它通过验证,请继续处理循环中的代码。我可能会在循环中执行3-5次。但是这就是......
当我像这样设置我的脚本时,它不能按预期工作:
for example in examples:
##### do some stuff here
##### then have a VALIDATION CHECK here
if "dates" in paydata:
continue
##### then do do some more stuff here
##### then have another VALIDATION CHECK here
if 'Payment' in pay_plan:
continue
##### then do do some more stuff here
##### then have another VALIDATION CHECK here
if 'Plan' in pay_plan:
continue
##### continue on with the script and do some stuff here, etc.
但是,当我基本上将我的if语句放入函数中,然后我的代码看起来如下(使用基于函数返回的if语句),它按预期工作。那么,我的问题是,为什么continue语句在第一个代码示例中做了一件事(不按预期工作),但DO在第二个代码示例中工作(按预期工作)。我在这个“头脑清醒”中缺少什么?
##### create validation-check functions
def func_1(id, paydata):
if "dates" in paydata:
return(True)
else:
return(False)
def func_2(id, pay_plan):
if 'Payment' in pay_plan:
return(True)
else:
return(False)
def func_3(id, plan):
if 'Plan' in plan:
return(True)
else:
return(False)
for example in examples:
#####
##### do some stuff here
#####
##### then have a VALIDATION CHECK here
md_check = multiple_dates(id, paydata)
if md_check == True:
continue
#####
##### then do do some more stuff here
#####
##### then have another VALIDATION CHECK here
on_pp = on_payment_plan(id, pay_plan)
if on_pp == True:
continue
#####
##### then do do some more stuff here
#####
##### then have another VALIDATION CHECK here
on_pp = on_payment_plan(id, plan)
if on_pp == True:
continue
#####
##### continue on with the script and do some stuff here
#####
答案 0 :(得分:0)
continue
没有按照您的想法行事。关键字continue
将循环发送回开头。它不会被用来允许循环继续,因为名称暗示它已经满足条件但你需要循环继续前进。
为了让你的循环继续进行更好的检查,格式为:
if not md_check:
break
如果你的情况不存在,这会颠倒你的逻辑并退出循环。这同样适用于此:
if on_pp == True:
continue
应该是:
if not on_pp:
break
一个小工作示例,展示continue
如何运作:
>>> x = 1
>>> while x < 50:
if not x & 1:
print('{} is even'.format(x))
x += 1
else:
print('{} is odd'.format(x))
x += 1
continue
print('this only prints if x is even')
1 is odd
2 is even
this only prints if x is even
3 is odd
4 is even
this only prints if x is even
5 is odd
6 is even
this only prints if x is even
7 is odd
8 is even
this only prints if x is even
9 is odd
10 is even
# snipped for brevity