SyntaxError:if语句中的语法无效

时间:2019-03-31 14:15:19

标签: python

尝试运行包含输入的脚本时,将其转换为float并针对某些if语句进行检查,但出现语法错误。

我不确定我对try-except语句和if语句中的条件的用法是否正确。我尝试在try-except语句上仅使用整数值和变体,但没有成功。我在Google上搜索了很多,语法似乎与我所看到的示例相符。

def computegrade():

    try:
        score = input(float('Enter score: '))

    except:
        print('Please enter a number!')

    else:
        if score <= 1 and score >= 0.9:
            grade = 'A'

        elif score <= 0.89 and >= 0.8:
            grade = 'B'

        elif score <= 0.79 and score >= 0.7:
            grade = 'C'

        elif score <= 0.69 and score >= 0.6:
            grade = 'D'

        elif score <= 0.59:
            grade = 'F'

        else:
            grade = 'Bad score'

    print(grade)


computegrade()

这是我得到的错误:

line 14
elif score <= 0.89 and >= 0.8:  
                        ^
SyntaxError: invalid syntax

编辑:更正了草率的错误(抱歉),现在改为:

Please enter a number!
Traceback (most recent call last):
  File "grade.py", line 32, in <module>
    computegrade()
  File "grade.py", line 29, in computegrade
    print(grade)
UnboundLocalError: local variable 'grade' referenced before assignment

以这种方式使用try是否不合适?似乎它不等待输入,这就是为什么从未分配成绩的原因?

3 个答案:

答案 0 :(得分:1)

按如下所示重新编写它,您错过了变量score

elif score <= 0.89 and score >= 0.8:
     grade = 'B'

答案 1 :(得分:0)

对于与elif相对应的B,您没有在score >= .8语句后输入and

仅供参考,您不需要任何and语句。 elif仅在之前的那个不执行时才会执行,因此您可以从elif链中的最高值或最低值开始,它仍然可以工作

不过,最好的方法可能是使用dictionary comprehension

答案 2 :(得分:0)

只需这样编码:

def computegrade():
    try:
        score = float(input('Enter score: '))
    except ValueError:
        print('Please enter a number!')
        return
    else:
        if 0.9 <= score <= 1:
            grade = 'A'
        elif 0.8 <= score <= 0.89:
            grade = 'B'
        elif 0.7 <= score <= 0.79:
            grade = 'C'
        elif 0.6 <= score <= 0.69:
            grade = 'D'
        elif score <= 0.59:
            grade = 'F'
        else:
            grade = 'Bad score(must be <=1)'
    print('Grade of score {score} is: {grade}'.format(**locals()))


if __name__ == '__main__':
    computegrade()

或更多pythonic:

GRADE_SCORE_RULE = {
    "A": [0.9, 1],
    "B": [0.8, 0.89],
    "C": [0.7, 0.79],
    "D": [0.6, 0.69],
    "F": [0, 0.59],
}


def score_to_grade(score):
    for k, v in GRADE_SCORE_RULE.items():
        if v[0] <= score <= v[1]:
            return k
    else:
        return "Bad score(must be <=1)"


def computegrade():
    try:
        score = float(input("Enter score: "))
    except ValueError:
        print("Please enter a number!")
        return
    else:
        grade = score_to_grade(score)
    if grade in GRADE_SCORE_RULE:
        print("Grade of score {score} is: {grade}".format(**locals()))
    else:
        print(grade)


if __name__ == "__main__":
    computegrade()