【问题标题】:Python invalid syntax error (2.7.5)Python 无效语法错误 (2.7.5)
【发布时间】:2013-07-28 05:16:49
【问题描述】:
clothes_total = tot1 + tot2 + tot3 + tot4+ tot5  
clothes_total1 = tot1 + tot2 + tot3+ tot4 + tot5
tot_price = tax * (clothes_total + shipping + gift_number)
tot_price1 = tax * (clothes_total1 * 0.85 + shipping + gift_number)
tot_price2 = tax * (clothes_total2 * 0.85 + shipping + gift_number - 30)
print "<h4>Original Price: $ %s </h4>" % clothes_total
if clothes_total < 150:
   print "<h4> TOTAL : %s </h4>" % tot_price
else clothes_total1 > 200:
  print "15% Discount + $30 off: $"
  print 0.85 * (clothes_total - 30)
  print "<h4> THIRTY: $ %s </h4>" % tot_price2

这是我的代码行,但在else clothes_total1 &gt; 200: 下,我不断得到:

无效的语法错误

不知道是什么问题。有人可以帮我帮忙吗?谢谢。

【问题讨论】:

  • 它有效!非常感谢!

标签: python syntax


【解决方案1】:

应该是elif 而不是else

elif clothes_total1 > 200:

来自docs

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

我认为你应该使用列表,而不是使用tot1 + tot2 + tot3 + tot4+ tot5

示例:

tot = [12,56,....] #some values

然后使用sum:

clothes_total = sum(tot)

如果列表有 5 个以上的项目,并且您想要前 5 个项目的总和,则使用切片:

clothes_total = sum(tot[:5])

【讨论】:

    【解决方案2】:

    else 不能有谓词。

    使用elif 而不是else

    elif clothes_total1 > 200:
    

    【讨论】:

      【解决方案3】:

      else 应该等于elif

      这是因为在 Python 中,else 充当一种“包罗万象”的角色——它不需要任何额外的要求,实际上也不允许它们。如果要为 else 子句指定 条件,则必须使用 elif

      【讨论】:

      • Python 没有else if
      【解决方案4】:

      else 不带条件,但 elif 带。 如果您使用 else,这意味着,如果一切都失败了,请执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-21
        • 2016-08-07
        • 2015-05-24
        • 2016-10-18
        • 1970-01-01
        相关资源
        最近更新 更多