语法错误python' if'和'其他'声明

时间:2017-10-04 05:22:41

标签: python if-statement

我的代码中出现此语法错误,我无法确定它是否为缩进错误或其他内容(https://i.stack.imgur.com/Alazd.png)。

# Creating a program that gives us the name,score and grade with variation in score and grade! A
name = input("Enter namez")
# print("name:", name)
print()

score = input("Enter scorez")
# print("score:", score)

score = int(score)
if score >= 75:
    grade = 'Excellent'
elif score >= 60:
    grade = 'Very good'
elif score >= 50
    grade = 'Quite good'
elif score >= 40
    grade = 'Not Bad'
elif score >= 30
    grade = 'Pretty Bad'
elif score >= 20
    grade = 'Horibble'
else: grade = 'Appauling'
print()

print('name:', name, 'score:', score, ' and grade:', grade)
print()

print('So,', name, 'you got a score of', score, 'and hence culminates that your grade becomes', grade, '.')

3 个答案:

答案 0 :(得分:1)

您错过了":"在elif条件下和最后四个条件中,将缩进设置为4个空格。

答案 1 :(得分:1)

您在semi-colons (:)条件下缺少elif。然后,在grade的最后3次分配中,缩进也不正确。

答案 2 :(得分:1)

使用适当的缩进来标记代码块。

您的elif语句缺少冒号。

http://www.python.org/dev/peps/pep-0008/#other-recommendations

  

始终围绕这些二元运算符,两边都有一个空格:赋值(=),扩充赋值(+ =, - =等),比较(==,<,>,!=,<> ;,< =,> =,in,not in,is,is not),布尔(和,或者,不是)。

例外情况是=用于设置命名参数。

也就是说,您可以将代码转换为可重用的函数。

def grade(score):
    """ Return a grade based on score."""

    rank = ''

    if score >= 75:
        rank = 'Excellent'
    elif score >= 60:
        rank = 'Very good'
    elif score >= 50:
        rank = 'Quite good'
    elif score >= 40:
        rank = 'Not bad'
    elif score >= 30:
        rank = 'Pretty bad'
    elif score >= 20:
        rank = 'Horrible'
    else:
        rank = 'Appalling'

    return rank

name = input('Enter name: ')
score = int(input('Enter score: '))    
report_card = {'Name': name, 'Score': score, 'Grade': grade(score)}

print(report_card)

试运行:

Enter name: X
Enter score: 90
{'Name': 'X', 'Score': 90, 'Grade': 'Excellent'}