Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c290344

Browse files
Create kc36.md
1 parent c6991fe commit c290344

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

‎kc/kc36.md‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# 3-6 break、continue循环中断
2+
前面的章节里,咱们学习了for及 while 的用法,这时候,相信大家肯定会有疑问,在循环当中我能不能根据条件语句来控制循环的走向哪?
3+
4+
当然是可以!
5+
6+
- **break 中断全部循环,跳出全部循环,执行后面的代码**
7+
- **continue 跳出本次循环(仅是本次),执行下一次循环,还在循环内**
8+
## 1.break 用法
9+
break 用来中断循环,也可以理解为跳出循环,执行循环体之外的代码,
10+
11+
比如我想定义一个计数闹钟,当闹钟是6点时,我要中断循环,开始起床
12+
### 代码区 1
13+
```python
14+
1 # break用法演示
15+
2 x = 0 # 定义一个小时变量
16+
3 while(True): # 一个while死循环,必须通过break退出
17+
4 print(x) # 输出几点了
18+
5 if(x >= 6): # 判断条件是否到6点了
19+
6 print('开始起床')
20+
7 break # while循环被打断,跳出整个while循环
21+
8 x = x + 1
22+
9 print('我是循环之外的代码 !')
23+
```
24+
![4](https://user-images.githubusercontent.com/103555341/163546933-bee710b5-943e-454e-b00d-922d2b897614.jpg)
25+
```python
26+
0
27+
1
28+
2
29+
3
30+
4
31+
5
32+
6
33+
开始起床
34+
我是循环之外的代码 !
35+
```
36+
### 代码区 2
37+
```python
38+
1 # break用法演示
39+
2
40+
3 for i in range(6): # for循环开始 原本是 从0到5
41+
4 if i>2: break # i等于3时,满足 i>2, break语句完全退出循环
42+
5 print(i) # 实际打印输出的是 0,1,2 少了 3,4,5
43+
6
44+
7 print('--end--')
45+
8
46+
```
47+
![4](https://user-images.githubusercontent.com/103555341/163546933-bee710b5-943e-454e-b00d-922d2b897614.jpg)
48+
```python
49+
0
50+
1
51+
2
52+
--end--
53+
```
54+
## 2.continue 用法
55+
continue 跳出本次的循环,执行下次循环
56+
### 代码区 3
57+
```python
58+
1 # continue用法演示
59+
2
60+
3 for x in range(6): # 构造一个从0-5的循环
61+
4 if x==0: continue # x等于0 跳过本次循环,重新回到for取数,不执行下面的print语句
62+
5 if x==4: continue # x等于4 跳过本次循环,不执行下面的print语句
63+
6 print(x) # 输出的结果可以看见少了 0 ,4
64+
7
65+
8 print('循环结束了')
66+
9 print(list(range(6))) # 显示一下过滤之前原本有几个元素
67+
10
68+
```
69+
![4](https://user-images.githubusercontent.com/103555341/163546933-bee710b5-943e-454e-b00d-922d2b897614.jpg)
70+
```python
71+
1
72+
2
73+
3
74+
5
75+
循环结束了
76+
[0, 1, 2, 3, 4, 5]
77+
```
78+
### 代码区 4
79+
```python
80+
1 # 练习题 按照上面的例子,拷贝到这来,改变参数运行一下,加深理解
81+
2
82+
```
83+
![4](https://user-images.githubusercontent.com/103555341/163546933-bee710b5-943e-454e-b00d-922d2b897614.jpg)
84+
85+
86+
87+
88+
89+
90+
91+
92+
93+
94+
95+
96+
97+
98+
99+
100+
101+
102+
103+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /