for嵌套循环中的执行顺序,第一步是先执行内层for check_1 in check:吗? 为什么返回的结果是有1, 2的。
来源:7-2 for与for-else循环

慕勒2572366
2018-08-25
testing_list = ([['football', 'basketball', 'ball', 'table ball'], [1, 2]])
for check in testing_list:
for check_1 in check:
if check_1 == 'football':
break
print(check_1)
else:
print('The selection is done!')
写回答
1回答
-
原代码:
testing_list = ([['football', 'basketball', 'ball', 'table ball'], [1, 2]]) for check in testing_list: for check_1 in check: if check_1 == 'football': break print(check_1) else: print('The selection is done!')
代码先执行最外层的for循环,如下代码
for check in testing_list:
第一次for循环 check 的值是:['football', 'basketball', 'ball', 'table ball']
第二次for循环 check 的值是:[1, 2]
把上面的两个列表分别放到内部的for循环内执行,如下代码:
for check_1 in check: if check_1 == 'football': break print(check_1)
该for循环第一次将要遍历['football', 'basketball', 'ball', 'table ball']这个列表,且每次循环都会if进行判断
在第一次循环的时候 就触发了break 导致跳出循环,不再继续循环也不输出结果,结束了该列表的遍历输出,直接进入了[1, 2]的遍历输出当中。
最终将 1和2进行了输出 ...
注意:代码一般都是从上往下执行,从左往右执行,有赋值符号先执行赋值符号右侧的账表达式,有优先级关系会根据优先级依次进行计算。
这块你还不够熟练,建议多去看几遍之前有关for循环的课程,多敲敲多练练。
212018-08-27
相似问题