break,exit,continue,pass区别详细说明(python3)

时间:2022-06-02 00:15:33

pass :占位符,无任何操作。

continue: 跳出本次循环

break:结束本次循环

exit():结束整个程序

pass占位符无任何操作,可以用Python内置文档测试模块测试,无报错就正确(doctest严格按照Python交互式命令行的输入和输出来判断测试结果是否正确)

'''
>>> num=1
>>> while num<5:
...     num+=1
...     if num==3:
...         pass
...         print (num)
...     print (num)
... 
2
3
3
4
5
'''
if __name__=='__main__':
    import doctest
    doctest.testmod()

pass只占位,相当于执行2次print 3

continue退出本次循环

>>> num=1
>>> while num<5:
...     num+=1
...     if num==3:
...         continue
...         print (num)
...     print (num)
...
2
4
5
'''
if __name__=='__main__':
    import doctest
    doctest.testmod()

跳出本次循环不执行if里面print,继续执行whlie

break结束本循环 (后面这2个例子包涵input。勿使用doctext)

>>> age=20
>>> for i in range(4):
...     print (i)
...     while True:
...         num1=input('please input:')
...         if int(num1) <age:
...             print ('the num greater')
...         elif int(num1)>age:
...             print ('the num litter')
...         else:
...            break
...            print ('guess the num')
...
0
please input:20
1
please input:20
2
please input:20
3
please input:20

break结束本内循环while循环,直接退出到外循环for中,执行完range(4)才结束。

exit直接退出

>>> age=20
>>> for i in range(4):
...     print (i)
...     while True:
...         num1=input('please input:')
...         if int(num1) <age:
...             print ('the num greater')
...         elif int(num1)>age:
...             print ('the num litter')
...         else:
...            exit()
...            print ('guess the num')
... 
0
please input:20

exit直接退出整个程序。