使用 while 进行循环
Python 中最简单的循环机制是 while。
>>> count = 1
>>> while count <= 5:
... print(count)
... count += 1
...
1
2
3
4
5
>>>
首先将变量 count 的值赋为 1,while 循环比较 count 的值和 5 的大小关系,如果 count 小于等于 5 的话继续执行。在循环内部,打印 count 变量的值,然后使用语句 count += 1 对count 进行自增操作,返回到循环的开始位置,继续比较 count 和 5 的大小关系。现在,
count 变量的值为 2,因此 while 循环内部的代码会被再次执行,count 值变为 3 。
在 count 从 5 自增到 6 之前循环一直进行。然后下次判断时,count <= 5 的条件不满足,while 循环结束。Python 跳到循环下面的代码。
使用break跳出循环
如果你想让循环在某一条件下停止,但是不确定在哪次循环跳出,可以在无限循环中声明break 语句。
这次,我们通过 Python 的 input() 函数从键盘输入一行字符串,然后将字符
串首字母转化成大写输出。当输入的一行仅含有字符 q 时,跳出循环 :
while True:
msg = input('please input somethings: ')
if msg == 'q':
break
print(msg.title())
please input somethings: fsead
Fsead
please input somethings: fdsa
Fdsa
please input somethings: fsd
Fsd
please input somethings: fsdafsd
Fsdafsd
please input somethings: fsd
Fsd
please input somethings: fsd
Fsd
please input somethings: q
Process finished with exit code 0
使用continue跳到循环开始
有时我们并不想结束整个循环,仅仅想跳到下一轮循环的开始。这时可以使用continue
count = 0
while count < 10:
if count == 4: # 打印0-9 除了可能有人不喜欢的数字 4
count += 1
continue
print(count)
count += 1
0
1
2
3
5
6
7
8
9
Process finished with exit code 0
循环外使用else
如果 while 循环正常结束(没有使用 break 跳出),程序将进入到可选的 else 段。
>>> numbers = [1, 3, 5]
>>> position = 0
>>> while position < len(numbers):
... number = numbers[position]
... if number % 2 == 0:
... print('Found even number', number)
... break
... position += 1
... else: #没有执行break
... print('No even number found')
...
No even number found