【问题标题】:Invalid syntax in Python when calling variable调用变量时Python中的语法无效
【发布时间】:2018-04-30 18:25:42
【问题描述】:

当我给它一个特定的考试分数和出勤率时,我试图让代码显示 B 级和 C 级。但是,它没有这样做。不过A级是完美的。尽管我在上面的两行中使用了相同的“语法”并且它不起作用,但它为考试分数提出了一个无效的语法错误。我只是 Python 新手,这是我的第一个项目之一。

examscore = int(input(("Enter exam score: ")))
attendance = int(input(("Enter attendance: ")))

if examscore >90 and attendance >90:
     print("Grade A")

elif examscore >80 or <=90 and attendance >90:
     print("Grade B")

elif examscore >70 or <=80 and attendance >90:
     print("Grade C")

这是我得到的错误。

SyntaxError: invalid syntax

提前致谢。

【问题讨论】:

标签: python variables syntax


【解决方案1】:

实际上,您根本不需要检查上限,因为它总是被之前的检查覆盖,并且您使用的是elif

examscore = int(input(("Enter exam score: ")))
attendance = int(input(("Enter attendance: ")))

if examscore >90 and attendance >90:
     print("Grade A")

elif examscore >80 and attendance >90:
     print("Grade B")

elif examscore >70 and attendance >90:
     print("Grade C")

【讨论】:

    【解决方案2】:

    你需要:

    elif examscore >80 or examscore <= 90 and attendance >90:
    

    代替:

    elif examscore >80 or <= 90 and attendance >90:
    

    【讨论】:

    • 不正确。例如,examscore == 75attendance &gt; 90 将报告 Grade B
    【解决方案3】:

    你不能写elif examscore &gt;80 or &lt;=90,正确的语法是elif examscore &gt;80 &lt;=10

    【讨论】:

      【解决方案4】:

      你有几个问题。

      首先:

      examscore >80 or <=90 and attendance >90
      

      不是有效的语法。把它想象成[examscore &gt; 80] OR [ &lt;= 90 ] AND [attendance &gt; 90]。我想你会看到[ &lt;= 90 ] 不是可以评估的东西。相反,它应该说[examscore &lt;= 90 ]

      其次,不同的语言在“绑定”AND 和 OR 条件方面遵循不同的规则。没有括号,很难确定您打算如何评估此逻辑。我猜测你希望的是:

          examscore > 80 or (examscore <=90 and attendance > 90)
      

      这意味着任何得分超过 80 分或低于 90 分但出勤率超过 90 分的人都会获得“B”(这是获得 B 的一个有趣指标 - 他们可以得分 0,并且只要他们在课堂上,他们在哪里得到“B”?——但这与你的问题无关)。没有括号,很难确定。

      【讨论】:

      • 我怀疑这是否是预期的。我认为应该是and 而不是or
      【解决方案5】:

      您的语法错误是由于无效的or 条件造成的。 &lt;= 期望双方都有变量。

      elif examscore >80 or <=90 and attendance >90:  # Error here
           print("Grade B")
      
      elif examscore >70 or <=80 and attendance >90:  # Here as well
           print("Grade C")
      

      您可以通过使用来解决此问题

      elif 80 < examscore <= 90 and attendence > 90:
      

      【讨论】:

        猜你喜欢
        • 2017-06-22
        • 2019-07-21
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 2018-10-18
        • 1970-01-01
        • 2012-10-04
        • 2011-12-06
        相关资源
        最近更新 更多