解决雪茄和松鼠难题在编码蝙蝠抛出语法错误



我正在尝试解决这个编码蝙蝠问题:

喜欢聚会的松鼠聚在一起抽雪茄。只有当工作日的雪茄数量在 40 到 60 支之间时,这样的聚会才被认为是成功的。然而,在周末,雪茄的数量没有上限。编写一个函数,如果具有给定值的参与方成功,则返回 True。

不幸的是,尽管我偶尔使用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 和表达式的其余部分之间不应有冒号。

首先,正如 tcdowney 指出的那样,语法是 elif,而不是其他,其次,你需要在 elif 语句中使用逻辑评估器,而不是作为某种操作。最后,在等号之前有大于/小于号。

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

这应该可以解决问题;)

def cigar_party(cigars, is_weekend):
  a = range(61)
  if is_weekend and cigars not in a:
    return True
  elif cigars in range(40,61):
    return True
  else:
    return False
def cigar_party(cigars, is_weekend):
   if is_weekend and cigars>=40:
     return True
   elif not is_weekend and cigars in range(40,61):
     return True
   return False
def cigar_party(cigars, is_weekend):
    if is_weekend:
        return cigars >= 40
    return 40 <= cigars <= 60  // Python supports this type of Boolean evaluation

或使用三元形式:

def cigar_party(cigars, is_weekend):
    return cigars >= 40 if is_weekend else 40 <= cigars <= 60
def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars>=40:
      return is_weekend
  else:
    if cigars in range(40,61):
      return True
  return False
def cigar_party(cigars, is_weekend):
  if is_weekend == True:
    if cigars >= 40:
      return True
    else:
      return False
  if is_weekend == False:
    if cigars >= 40 and cigars <= 60:
      return True
    else:
      return False
#got 9/12 not bad! 
is_weekday = True
is_weekend = True 

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

最新更新