简体   繁体   中英

What is the if-else indentation when we use “break” in the if block?(in Python)

I ran the following code and there is no problem.

for i in range(1,10):
  if i%5 == 0: break
  print(i)
else:
  print("for else")

But I want to know why a SyntaxError occurs when if block and else block are aligned? I mean the following code that gives an error during execution.

for i in range(1,10):
  if i%5 == 0: break
  print(i)
  else:
  print("for else")

The if could be followed immediately by an else: but you have a print between them.

It may be clearer if you reformat this with consistent indentation. I'm leaving out the print to illustrate two different options.

for i in range(1,10):
  if i%5 == 0:
      break
  else:
      print("for else")

Here, the else: is taken if the if condition is false, each time the loop is executed.

for i in range(1,10):
  if i%5 == 0:
      break
else:
  print("for else")

Here, the else: belongs to the for , and is taken when you exit the for loop if its body was never executed completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM