《Python编程:从入门到实践(第二版)》自学笔记(十一)

While循环

编程界的三大循环:if、for、while。if之前是在遍历的时候开始接触,for之前是在元素是否在列表中开始接触,而while从此刻开始认识。while循环是不断运行,直到指定的条件不满足为止。

1
2
3
4
5
6
7
8
9
10
current_number = 1 
while current_number <= 5:
print(current_number)
current_number += 1
输出:
1
2
3
4
5

当然,无限的循环在程序中执行时,也会受到人为的干扰或者终止。其中,我们也可以在被执行程序中添加由用户决定什么时候停止循环

1
2
3
4
5
6
7
8
9
10
prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
输出:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

为使被执行程序,更加简洁直接,因为上述代码中,美中不足的是:将quit也作为输出展示了出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
输出:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

那么对于有些被执行程序,并不是被编码完成后就必须要进行执行,一般是达到某个条件或者说是触发了某个开关后,再去执行。我们把这一过程称作为:标志(相当于总开关)

1
2
3
4
5
6
7
8
9
prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)

假设一下:如果循环正在进行,人为的立即退出循环,可否实现?通常利用break去实现。

break语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
prompt = "\nPlease enter the name of a city you have visited:" 
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city.title()}!")
输出:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit

当然,break语句不仅仅局限于用于while循环中,在Python的任意循环中都可以使用。

既然有退出,相对应的就有继续,continue。要返回循环开头,并根据条件测试结果决定是否继续执行循环,就可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。

1
2
3
4
5
6
7
8
9
10
11
12
current_number = 0 
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
输出:
1
3
5
7
9
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2024 Carrol Chen
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信