Python 流控爆发混乱
Python flow control break out confusion
我试图理解一个复杂的流程控制,但我无法开始工作,所以简化了它,但也不理解它的工作原理。
简化的流量控制为:
smurf = True
print('smurf status: ', smurf)
jackets = list(range(5))
print(jackets)
for j in jackets:
print('la la la la', j, '\n')
while smurf is True:
print('jacket is :', j)
if j == jackets[-3]:
smurf = False
break
print('smurf is FALSIOOOO')
j += 1
print('smurf with jacket ',j-1, ' be ok')
print('END OF SMURFGATE')
输出为:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
jacket is : 1
smurf with jacket 1 be ok
jacket is : 2
la la la la 1
la la la la 2
la la la la 3
la la la la 4
END OF SMURFGATE
我认为会发生(但没有发生)的是,一旦第 j 次迭代达到测试条件,while 循环将停止,流程控制将跳到脚本的最后一行并打印 'END OF SMURFGATE'。
期望的输出:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
la la la la 1
jacket is : 1
smurf with jacket 1 be ok
la la la la 2
jacket is : 2
END OF SMURFGATE
您错过了 for 循环的一个额外中断,现在您只中断了 while 循环。试试这个:
smurf = True
print('smurf status: ', smurf)
jackets = list(range(5))
print(jackets)
for j in jackets:
print('la la la la', j, '\n')
while smurf is True:
print('jacket is :', j)
if j == jackets[-3]:
smurf = False
break
print('smurf is FALSIOOOO')
j += 1
print('smurf with jacket ',j-1, ' be ok')
break # To escape the for-loop
print('END OF SMURFGATE')
输出:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
jacket is : 1
smurf with jacket 1 be ok
jacket is : 2
END OF SMURFGATE
我试图理解一个复杂的流程控制,但我无法开始工作,所以简化了它,但也不理解它的工作原理。
简化的流量控制为:
smurf = True
print('smurf status: ', smurf)
jackets = list(range(5))
print(jackets)
for j in jackets:
print('la la la la', j, '\n')
while smurf is True:
print('jacket is :', j)
if j == jackets[-3]:
smurf = False
break
print('smurf is FALSIOOOO')
j += 1
print('smurf with jacket ',j-1, ' be ok')
print('END OF SMURFGATE')
输出为:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
jacket is : 1
smurf with jacket 1 be ok
jacket is : 2
la la la la 1
la la la la 2
la la la la 3
la la la la 4
END OF SMURFGATE
我认为会发生(但没有发生)的是,一旦第 j 次迭代达到测试条件,while 循环将停止,流程控制将跳到脚本的最后一行并打印 'END OF SMURFGATE'。
期望的输出:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
la la la la 1
jacket is : 1
smurf with jacket 1 be ok
la la la la 2
jacket is : 2
END OF SMURFGATE
您错过了 for 循环的一个额外中断,现在您只中断了 while 循环。试试这个:
smurf = True
print('smurf status: ', smurf)
jackets = list(range(5))
print(jackets)
for j in jackets:
print('la la la la', j, '\n')
while smurf is True:
print('jacket is :', j)
if j == jackets[-3]:
smurf = False
break
print('smurf is FALSIOOOO')
j += 1
print('smurf with jacket ',j-1, ' be ok')
break # To escape the for-loop
print('END OF SMURFGATE')
输出:
smurf status: True
[0, 1, 2, 3, 4]
la la la la 0
jacket is : 0
smurf with jacket 0 be ok
jacket is : 1
smurf with jacket 1 be ok
jacket is : 2
END OF SMURFGATE