【问题标题】:If, elif, else conditions [closed]if,elif,else条件[关闭]
【发布时间】:2019-06-28 16:36:51
【问题描述】:

我正在处理 CodingBat 问题以更好、更有效地学习,而我面临的问题是:

Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.


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
  elif negative and (a<0 and b<0)
    return True
  else:
    return False

但我明白了

Compile problems:


invalid syntax (line 4)

作为错误。 CondaBat 给出的解决方案是:

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))

我看到 给出的示例代码与我的相比更快更有效,但我不明白为什么我的 elif 语句返回错误。

【问题讨论】:

  • elif 行末尾缺少分号。
  • 我想我需要睡觉
  • 短:return a &lt; 0 and b &lt; 0 if negative else a * b &lt; 0
  • 请注意,您的代码在逻辑上与示例不等价。
  • @molbdnilo:a * b &lt; 0 可以替换为(a &lt; 0) ^ (b &lt; 0)。当然,稍微长一点,但更直接地描述了目标,并且由于使用位运算符的bools 仍然产生bools,而不是ints,它按预期工作。这种方法避免了仅仅为了检查输入的符号而计算潜在的巨大产品的需要。您也可以将a &lt; 0 and b &lt; 0 更改为(a &lt; 0) &amp; (b &lt; 0) 以匹配,但您只会为了对称而这样做;它没有真正的性能或可读性优势。

标签: python if-statement boolean


【解决方案1】:

elif 后面少了一个冒号

def pos_neg(a, b, negative):
  if (a<0 and b>0) or (a>0 and b<0):
    return True
  elif negative and (a<0 and b<0): # <- was here
    return True
  else:
    return False

【讨论】:

  • 现在觉得好傻,非常感谢
猜你喜欢
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
相关资源
最近更新 更多