簡體   English   中英

這兩個代碼之間的區別?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM