python if else语句执行顺序问题
问题描述:
class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
ln = len(gas)
for i in range(ln):
if gas[i] < cost[i]:
continue
total = 0
for j in range(i, i + ln):
j %= ln
total += gas[j] - cost[j]
if total < 0:
break
else: #请问这个else是接着同缩进的if嘛?为什么这个else可以和if中间隔着其他语句
return i
return -1
答
这个else子句是循环结构for...else语句结构的一部分,只有正常循环完所有次数,才会执行 else ,break 可以阻止 else 语句块的执行。参考:https://zhuanlan.zhihu.com/p/37374055, 以及这里:https://book.pythontips.com/en/latest/for_-_else.html
答
else可以和for循环同一层级别的