簡體   English   中英

用python中的函數返回true或false

[英]returning true or false with function in python

您能解釋一下我的代碼為什么錯誤嗎? 另外,我不太了解解決方案代碼的工作原理,請解釋一下。 這是一個練習:給定2個int值,如果一個為負且一個為正,則返回True。 除非參數“ negative”為True,否則僅當兩個參數均為負時才返回True。

pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True

這是我的代碼:

def pos_neg(a, b, negative):
  if (a < 0 and b > 0) or (a > 0 and b < 0):
    return True
  if negative==True:
    if a < 0 and b < 0:
      return True
  return False

這是解決方案:

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))

在第一個if語句中,如果一個為正,一個為負,則立即返回True ,甚至不檢查negative是否為True 相反,您應該首先檢查negative參數(並檢查ab都為負),然后檢查是否為負或正。

如果a為負數, b為正數,並且negativeTrue ,則您的代碼將失敗。

要解釋為什么代碼不等同於解決方案,請參閱調用pos_neg(-1, 1, True)時發生的情況。 解決方案看到負數為true,然后檢查a < 0 and b < 0是否均不小於0,因此返回False 您的代碼首先檢查它們是否具有不同的符號,因為它們相同,所以返回true。 僅當它們具有相同的符號時,才檢查負輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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