在for循环中使用if-else

时间:2018-12-03 16:22:57

标签: python-3.x for-loop if-statement

marks = [10, 20, 70, 81, 14, 78, 5, 95]
for i in marks:
    if i < 40:
        print('You have failed and secured {} marks'.format (i))
else:
    print("You passed with {} marks".format (i))


OUTPUT::
You have failed and secured 10 marks
You have failed and secured 20 marks
You have failed and secured 14 marks
You have failed and secured 5 marks
You passed with 95 marks

在for循环后执行循环时如何在else循环中使用else?

2 个答案:

答案 0 :(得分:1)

您的代码缩进不正确,应该像这样:

marks = [10, 20, 70, 81, 14, 78, 5, 95]
for i in marks:
    if i < 40:
        print('You have failed and secured {} marks'.format (i))
    else:
        print("You passed with {} marks".format (i))

Python未使用大括号,因此缩进至关重要。

答案 1 :(得分:1)

看起来缩进不正确,以下应该可行

for i in marks:
   if i < 40:
       print('You have failed and secured {} marks'.format (i))
   else:
       print("You passed with {} marks".format (i))