python learning, break and continue

python break and continue

break and continue are generally used together with loop structures, etc., both indicate exiting the loop, but there are differences

break

1
2
3
4
5
6
7
num_arr = [1, 9, 2, 4, 5, 10, 7]

for num in num_arr:
   if num >= 5:
     break

   print(num)

Save as helloworld.py, and execute the result

1
2
[me@VM_0_14_centos python] # python helloworld.py
1

From the results, only 1 is printed

break is to exit and terminate all loops, and continue to execute the statement after the loop

continue

Also slightly modify the above test case and change break to continue

1
2
3
4
5
6
7
num_arr = [1, 9, 2, 4, 5, 10, 7]

for num in num_arr:
   if num >= 5:
     continue

   print(num)

Save as helloworld.py, and execute the result

1
2
3
4
[me@VM_0_14_centos python] # python helloworld.py
1
2
4

From the results, all elements greater than or equal to 5 are printed.

continue means to abort the current loop, that is, when the continue is encountered, the code after the loop

continues is no longer executed

Continue to the next cycle

Persist in original technology sharing, your support will encourage me to continue to create!