【python:循环终止命令】return;continue&break&exit();pass在循环中的区别

1.return

return只能出现在定义函数体中,作用为:

终止函数的执行,并且返回函数的值

*【在循环体中的return】:

在绝大多数情况下,当函数体内的程序执行到return这一步时,会退出函数,即使是在一个循环体内,程序也不会再执行(即返回第一次循环的数值),可以通过一个例子来简单验证一下:

def deduplication(n):
    for i in range(n):
        return i
print(deduplication(10))

运行结果:

E:\anaconda3\envs\mne\python.exe C:/Users/a/Desktop/leetcode/test.py
0

Process finished with exit code 0

可以看到,return只返回了第一次循环,i=0的时候的结果便中止程序了

2.continue&break&exit,作用范围continue<break<exit

continue 语句仅跳出符合if条件的某次小循环,当下一次小循环不符合if条件时,仍继续执行循环;

而break则跳出整个大循环;

exit作用范围则更大,可以直接终止整个程序。

举例:

continue:

for str in 'python':
    if str == 'h':
        continue
    print(str)

输出结果,可以看到当满足if条件时,跳出了“h”字母的单次循环,但仍进行下一次的循环

E:\anaconda3\envs\mne\python.exe C:/Users/a/Desktop/leetcode/test.py
p
y
t
o
n

Process finished with exit code 0

break:

for str in 'python':
    if str == 'h':
        break
    print(str)

输出结果,执行到‘h’字母后便不在执行,跳出循环:

E:\anaconda3\envs\mne\python.exe C:/Users/a/Desktop/leetcode/test.py
p
y
t

Process finished with exit code 0

exit()(与break比较):

for i in range(2):
    print(i)
    for str in 'python':
        if str == 'h':
            break
        print(str)

输出结果,跳出了该循环不继续执行该循环后面内容,但继续执行嵌套的大循环:
E:\anaconda3\envs\mne\python.exe C:/Users/a/Desktop/leetcode/test.py
0
p
y
t
1
p
y
t

Process finished with exit code 0
for i in range(2):
    print(i)#end=''表示不换行输出
    for str in 'python':
        if str == 'h':
            exit()
        print(str)

输出结果,直接终止所有循环:
E:\anaconda3\envs\mne\python.exe C:/Users/a/Desktop/leetcode/test.py
0
p
y
t

Process finished with exit code 0

3.pass

pass 是空语句,是为了保持程序结构的完整性。

pass 不做任何事情,一般用做占位语句。

def sample(n_samples):
    pass

该处的 pass 便是占据一个位置,因为如果定义一个空函数程序会报错,当你没有想好函数的内容是可以用 pass 填充,使程序可以正常运行


版权声明:本文为qq_32793161原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。