Python · 流程控制

简介

Python 有三种控制流语句: ifforwhile,两种相关语句:breakcontinue

  • if
  • while
  • for
  • break
  • continue

流程控制

if

if 语句用以条件检查:如果条件为 true,将运行一块语句,否则运行另一块语句,其中 else 从句是可选的。

示例if.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
number = 23
guess = int(input('Enter an integer : '))

if guess == number:
# 新块从这里开始
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# 新块在这里结束
elif guess < number:
# 另一代码块
print('No, it is a little higher than that')
# 你可以在此做任何你希望在该代码块内进行的事情
else:
print('No, it is a little lower than that')
# 你必须通过猜测一个大于(>)设置数的数字来到达这里。

print('Done')
# 这最后一句语句将在 if 语句执行完毕后执行。

输出:
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done

$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done

$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

while

while 语句能够让你在条件为真的前提下重复执行某块语句,while 语句是循环(Looping)语句的一种。

示例while.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
number = 23
running = True

while running:
guess = int(input('Enter an integer : '))

if guess == number:
print('Congratulations, you guessed it.')
# 这将导致 while 循环中止
running = False
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# 在这里你可以做你想做的任何事

print('Done')

输出:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

for

for...in 语句是另一种循环语句,其特点是会在一系列对象上进行遍历。

示例for.py

1
2
3
4
5
6
7
8
9
10
11
12
for i in range(1, 5):
print(i)
else:
print('The for loop is over')

输出:
$ python for.py
1
2
3
4
The for loop is over

break

break 语句用以中断循环语句,也就是中止循环语句的执行。

示例break.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')

输出:
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

continue

continue 语句用以跳过当前循环块中的剩余语句,并继续该循环的下一次迭代。

示例continue.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
# 自此处起继续进行其它任何处理

输出:
$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit