【发布时间】:2021-11-07 17:47:44
【问题描述】:
我正在努力得到答案m = [0, 2, 0, 4, 0]:
m = []
while True:
for x in range(1, 6):
if x == 2:
m.append(x)
continue
else:
m.append(0)
continue
if x == 4:
m.append(x)
continue
else:
m.append(0)
continue
break
print(m)
答案来了m = [0, 2, 0, 0, 0]
【问题讨论】:
-
你可能会考虑使用类似Python Tutor 的东西来可视化这个程序的执行。
-
while循环的意义何在? -
这里需要
elif。if x == 2:/elif x == 4:/else:。您的代码永远不会超过第一个 if 语句。 -
是的,他们不应该这样做。他还可以完全删除第一个
else:子句来解决问题,但正确答案是if/elif/else没有continues。 -
IF x == 2 做某事并继续 ELSE 做其他事情并继续 - 后面的 if x==4 永远不会执行,因为您的代码“继续”回到 while 循环。如果你修复到 if/elif/else 就不需要继续了