问题描述
def Dishlist_all_cheap(d: [Dish], x: int):
for i in d:
if Dish_is_cheap(i, x) == False:
return False
return True
与
def Dishlist_all_cheap(d: [Dish], x: int):
for i in d:
if Dish_is_cheap(i, x) == False:
return False
else:
return True
为什么以及“返回真”语句的位置如何重要? 出于背景目的,函数Dish_is_cheaper表示菜肴是否比标价便宜,而Dishlist_all_cheap说明列表中的所有菜肴是否比标价便宜。
1楼
此代码无法正常运行:
def Dishlist_all_cheap(d: [Dish], x: int):
for i in d:
if Dish_is_cheap(i, x) == False:
return False
else:
return True
因为如果列表的第一个Dish
便宜,它将返回True
。
如果所有的Dish
都便宜,您想返回True
正是这段代码很好地做到了:
def Dishlist_all_cheap(d: [Dish], x: int):
for i in d:
if Dish_is_cheap(i, x) == False:
return False
return True
它返回True
,如果Dish_is_cheap(i, x)
永远是True
为所有的菜。