Skip to main content
 首页 » 编程设计

python之if、elif、else 条件

2024年11月24日7pander-it

<分区>

我正在处理 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 语句返回错误。