Skip to main content
 首页 » 编程设计

python之CodingBat 上的雪茄和松鼠拼图抛出语法错误的解决方案

2025年05月04日17zhenyulu

我正在尝试解决 this CodingBat问题:

Squirrels who like to party get together and smoke cigars. Such a party is only deemed successful when the number of cigars is between 40 and 60, on a weekday. On weekends, however, there is no upper bound on number of cigars. Write a function that returns True if the party with the given values was successful.

不幸的是,虽然我偶尔使用过 Python,但我对它的了解还不够好,无法理解为什么我的代码会因第 5 行的语法错误而失败:

def cigar_party(cigars, is_weekend): 
  if is_weekend: 
    if cigars >= 40: 
      return True 
  else if: 
    cigars >= 40 and cigars =< 60: 
      return True 
  else: 
    return False 

请您参考如下方法:

在 Python 中你需要使用 elif而不是 else if .

更多信息: http://docs.python.org/2/tutorial/controlflow.html

同时更改以下行:

else if: 
cigars >= 40 and cigars =< 60: 

对此:

elif cigars >= 40 and cigars <= 60: 
    return True 

小于等于号需要为<=关键字 elif 和表达式的其余部分之间不应有冒号。