[英]python: if - in operator. Is there a difference between these two codes?
[英]Difference between these two codes?
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說明列表中的所有菜餚是否比標價便宜。
此代碼無法正常運行:
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
為所有的菜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.