For
Else
The For loop executes the Else statement if it ends normally.
We write a for...else-type statement as follows:
#!/usr/local/python3/bin/pythonfor i in range(10): print(i)else: print(‘main end‘)
After the run we will find that, in this case, the content after else is executed:
[[email protected] ~]# python forE.py0123456789main end
Then we set a pause as follows:
#!/usr/local/python3/bin/pythonimport timefor i in range(10): print(i) time.sleep(1)else: print(‘main end‘)
When running, we use "CTRL + C" to exit, as follows:
[[email protected] ~]# python forE.py01^CTraceback (most recent call last): File "forE.py", line 6, in <module> time.sleep(1)KeyboardInterrupt[[email protected] ~]#
As can be seen from the above results, the program exits after an exception is thrown, the keyboard is interrupted, at this time else after the content is not executed.
So now that we set the program to exit at a certain place, what should we do? Now let's set a time when I equals 5, then exit the loop, and then we can use the break in the For loop:
#!/usr/local/python3/bin/pythonimport timefor i in range(10): print(i) if i==5: break else: print(‘main end‘)
After running we will find that the value of I does not run back to 5, and else's content is not executed:
[[email protected] ~]# python forE.py012345[[email protected] ~]#
We can also add some content, when I equals 3 continue, when I equals 6 can write a pass, to occupy a position:
#!/usr/local/python3/bin/pythonimport timefor i in range(10): if i==3: continue #有了continue,循环后面的语句都不会执行了 elif i==5: continue elif ==6: pass #占位 print(i)else: print(‘main end‘)
After running we will find that 3 and 5 are not reflected in the results:
[[email protected] ~]# python forE.py01246789main end
If we write a code that lets the entire program exit in place of the placeholder, as follows:
#!/usr/local/python3/bin/pythonimport timeimport sysfor i in range(10): if i==3: continue #有了continue,循环后面的语句都不会执行了 elif i==5: continue elif i==6: sys.exit() #退出整个程序 print(i)else: print(‘main end‘)
Break exits the entire loop
Continue exits the current loop, then enters the next loop
Pass placeholder
Sys.exit () exit the entire script
Python for Loop exit