![](/img/trans.png)
[英]Python if statement always returns false, even though input is true
[英]If statement is always calculated as true even when it is false
我有以下循環:
for tile_id, tile in corner_tiles.items():
for neighbour in tile["neighbours"]:
if not (neighbour in enemy_tiles) and tile["player"] == None:
return tile_id
其中: tile
是形式為的字典
{'counters': <number of counters on tile or None>,
'player': <player id of the player who holds the tile or None>,
'neighbours': <list of ids of neighbouring tile>
}
和corner_tiles
和enemy_tiles
是{<tile_id> : <tile>, ... }
形式的字典。
循環總是返回tile_id
而不管neighbour
是否在enemy_tiles
tile["player"]
,但如果tile["player"]
不為None
則不會返回。 我已經嘗試了好一陣子了,但似乎無法發現我錯了。
編輯:
我也嘗試過:
for tile_id, tile in corner_tiles.items():
if tile["player"] is None:
for neighbour in tile["neighbours"]:
if neighbour not in enemy_tiles:
return tile_id
行為方式相同。
經過很大的壓力后,我發現了錯誤背后的簡單原因,並且因自己的錯誤而踢自己。
我的循環本應執行的操作是確保所有 neighbours
都不在enemy_tiles
。 當然,幾乎每次都將其評估為true,因為被檢查的第一個neighbour
不在enemy_tiles
可能性要高enemy_tiles
,因此該語句為true,並且僅在檢查了一個neighbour
之后才返回tile_id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.