search

Home  >  Q&A  >  body text

python - for else

a=[11,22,33,44,55]

for i in a:

print(i)

else:

print(99)

Result:
11
22
33
44
55
99
This is amazing Why does 99 appear
How should I write for if else?

学习ing学习ing2738 days ago1354

reply all(3)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-12 09:25:44

    1.for ... else ... syntax (http://book.pythontips.com/en...)

    for i in range(10):
        #如果没有break,会print所有i
        print(i)
    else:
        #如果上面的for循环没有break,这里会打印
        print(99)
    

    2.for if else should refer to the following:

    for i in range(10):
       if i > 5:
          break
       else:
          print(i)
      

    reply
    0
  • 代言

    代言2017-06-12 09:25:44

    In addition to common conditional judgments in other languages, else in python can also be used in loops. If the break statement is not executed in the for loop, the branch statement under else will be executed

    reply
    0
  • 阿神

    阿神2017-06-12 09:25:44

    Because the loop is allowed to complete normally, the else branch is also executed

    reply
    0
  • Cancelreply