[英]Better way to write nested try except python
有沒有更好的方法來寫這個而不像這樣嵌套?
try:
if find_path(graph, startPos, (targetX+1,targetY,targetX,targetY)):
print('YES')
except:
try:
if find_path(graph, startPos, (targetX,targetY+1,targetX,targetY)):
print('YES')
except:
try:
if find_path(graph, startPos, (targetX-1,targetY,targetX,targetY)):
print('YES')
except:
try:
if find_path(graph, startPos, (targetX,targetY-1,targetX,targetY)):
print('YES')
except:
print('NO')
您可以列出潛在坐標,然后在 for 循環中依次嘗試每個坐標,成功時打破循環:
success = "NO"
coords = ((targetX+1,targetY), (targetX,targetY+1), (targetX-1,targetY), (targetX,targetY-1))
for coord in coords:
try:
x, y = coord
find_path(graph, startPos, (x, y, targetX,targetY))
except:
pass
else:
# Set success state and break out of the for loop
success = "YES"
break
print(success)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.