有什么我可以返回而不是“无”的东西,这样它仍然可以迭代但为空吗? 有时我想返回两个值,但有时我只想返回一个值。
for distance in range(1, 8):
temp_cords = [(origin[0] - ((origin[0]-check[0])*distance)), (origin[1] - ((origin[1]-check[1])*distance))]
if temp_cords in all_locations:
return False, None #I want to return only 'False' here.
elif temp_cords in (white_locations + black_locations):
if white_turn:
if temp_cords in white_locations:
return True, (distance - 1) #But here, I want to return two values.
创建一个返回长度会根据不同条件变化的元组的函数从来都不是一个好的设计,因为调用者无法简单地将返回的元组解压缩到固定数量的变量中。
在您的情况下,最好不要返回布尔值,而是默认返回
return distance - 1
,然后:
return None
当 temp_cords in all_locations
为 True
时,调用者只需检查返回值是否为 None
来决定如何处理返回值try-except
块中的函数来处理 temp_cords in all_locations
为 True
时的条件。