我試圖得到答案m = [0, 2, 0, 4, 0]:
m = [] 。
while True:
for x in range(1, 6)。
if x == 2:
m.append(x)
繼續: m.append(x)
else:
m.append(0)
繼續: m.append(0)
if x == 4:
m.append(x)
繼續: m.append(x)
else:
m.append(0)
繼續: m.append(0)
break
print(m)
答案來了 m = [0, 2, 0, 0, 0]
uj5u.com熱心網友回復:
主要問題是你需要使用elif。你也不需要while回圈。
m = [] 。
for x in range(1, 6)。
if x == 2:
m.append(x)
elif x == 4:
m.append(x)
else:
m.append(0)
print(m)
但這似乎真的只需要檢查值是否能被2整除就可以了:
m = [] []
for x in range(1, 6)。
if x % 2 == 0:
m.append(x)
else:
m.append(0)
print(m)
用一個串列理解:
print([x if x % 2 == 0 else 0 for x in range(1, 6) ])
uj5u.com熱心網友回復:
continue陳述句干擾了你的條件。 你應該不使用else或者只使用if/elif/else:
if x == 2:
m.append(x)
繼續: m.append(x)
if x == 4:
m.append(x)
繼續: m.append(x)
m.append(0)
或者
if x == 2:
m.append(x)
elif x == 4:
m.append(x)
else:
m.append(0)
而且,考慮到你在x是2的時候和x是4的時候做同樣的事情,你可以使用一個or關系來減少代碼的重復:
if x == 2 or x ==4:
m.append(x)
else:
m.append(0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/309997.html
標籤:
