Python 流程控制

条件判断

​ 编程的目的是为了控制计算机能够像人脑一样工作,那么人脑能做什么,就需要程序中有相应的机制去模拟。人脑无非是数学运算和逻辑运算,对于逻辑运算,即人根据外部条件的变化而做出不同的反映。(比如,如果是红灯和黄灯就等一会儿,否则就过马路)

1、if…else… 条件判断

1
2
3
4
5
# 语法
if 条件:
执行代码1
else:
执行代码2

如果:女人的年龄 > 30 岁,那么:叫阿姨

1
2
3
4
age_of_girl=31

if age_of_girl > 30:
print('阿姨好')

如果:女人的年龄 > 30岁,那么:叫阿姨,否则:叫小姐

1
2
3
4
5
6
age_of_girl=18

if age_of_girl > 30:
print('阿姨好')
else:
print('小姐好')

如果:女人的年龄 >= 18 并且 < 22岁 并且 身高 >170 并且 体重 <100 并且 是漂亮的,那么:表白,否则:叫阿姨

1
2
3
4
5
6
7
8
9
age_of_girl = 18
height = 171
weight = 99
is_pretty = True
if 18 <= age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
print('表白...')
else:
print('阿姨好')

2、if 的嵌套使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 在表白的基础上继续:
# 如果表白成功,那么:在一起
# 否则:打印。。。

age_of_girl=18
height=171
weight=99
is_pretty=True

success=False

if 18 <= age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
if success:
print('表白成功,在一起')
else:
print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
print('阿姨好')

3、elif 的使用

1
2
3
4
5
6
7
8
9
10
11
if 条件1:
执行代码块1
elif 条件2:
执行代码块2
elif 条件3:
执行代码块3

......

else:  
执行最后的代码块
1
2
3
4
5
6
7
8
9
10
11
score=input('>>: ')
score=int(score)

if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 70:
print('普通')
else:
print('很差')

while 循环

1、while循环

作用:多次执行同一段代码

就让用户猜年龄的demo而言,若想实现支持可以让用户猜测三次的功能,则需要把代码copy三次,如果是10次,100次,甚至不限次数,那么整个程序将无限冗长。

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
36
age_of_oldboy = 48

guess = int(input(">>:"))

if guess > age_of_oldboy :
print("猜的太大了,往小里试试...")

elif guess < age_of_oldboy :
print("猜的太小了,往大里试试...")

else:
print("恭喜你,猜对了...")

#第2次
guess = int(input(">>:"))

if guess > age_of_oldboy :
print("猜的太大了,往小里试试...")

elif guess < age_of_oldboy :
print("猜的太小了,往大里试试...")

else:
print("恭喜你,猜对了...")

#第3次
guess = int(input(">>:"))

if guess > age_of_oldboy :
print("猜的太大了,往小里试试...")

elif guess < age_of_oldboy :
print("猜的太小了,往大里试试...")

else:
print("恭喜你,猜对了...")

此时,可以使用while循环来实现对同一段代码的多次调用

1
2
3
4
5
while 条件:    
# 循环体

# 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
# 如果条件为假,那么循环体不执行,循环终止
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#打印0-10
count=0
while count <= 10:
print('loop',count)
count+=1

#打印0-10之间的偶数
count=0
while count <= 10:
if count % 2 == 0:
print('loop',count)
count+=1

#打印0-10之间的奇数
count=0
while count <= 10:
if count % 2 == 1:
print('loop',count)
count+=1

2、使用标志位来控制while循环嵌套

1
2
3
4
5
6
7
tag=True 
  while tag:
    ......
    while tag:
      ........
      while tag:
        tag=False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#练习,要求如下:
# 1 循环验证用户输入的用户名与密码
# 2 认证通过后,运行用户重复执行命令
# 3 当用户输入命令为quit时,则退出整个程序

name='cdc'
password='123'

tag=True
while tag:
inp_name=input('用户名: ')
inp_pwd=input('密码: ')
if inp_name == name and inp_pwd == password:
while tag:
cmd=input('>>: ')
if not cmd:continue
if cmd == 'quit':
tag=False
continue
print('run <%s>' %cmd)
else:
print('用户名或密码错误')

3、死循环

当循环没有退出条件时,循环体会一直重复执行

1
2
3
4
5
6
import time
num=0
while True:
print('count',num)
time.sleep(1)
num+=1  

4、break与continue

break用于终止整个循环,即遇到break语句,跳出while循环

continue用于跳出当次循环,继续执行后面的循环

1
2
3
4
5
6
7
8
9
count = 1

while count <= 8:
if count == 4:
break
else:
print(count)

count += 1
1
2
3
4
# 执行结果
1
2
3
1
2
3
4
5
6
7
8
9
10
11
12
13
count = 1

while count <= 8:
if count == 4:
count += 1
print("aaaa")
continue
print("bbbb")

else:
print(count)

count += 1
1
2
3
4
5
6
7
8
9
# 执行结果
1
2
3
aaaa
5
6
7
8

对比上述两个例子可以发现,当程序执行到break时整个循环就直接结束了,但是当程序执行到continue时,只是跳过了当前的判断,还在继续往下循环。(注:continue之后的语句不会执行)

5、while-else

当while循环正常执行结束,即中间没有被break中止的话,else语句才会被执行

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
36
37
38
39
40
# 正常执行没有被break中止
count = 0
while count <= 5 :
count += 1
print("Loop",count)

else:
print("循环正常执行完啦")
print("-----out of while loop ------")

"""
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦
-----out of while loop ------
"""

#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5 :
count += 1
if count == 3:break
print("Loop",count)

else:
print("循环正常执行完啦")
print("-----out of while loop ------")

"""
输出

Loop 1
Loop 2
-----out of while loop ------
"""

6、while循环练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#1. 使用while循环输出1 2 3 4 5 6     8 9 10
#2. 求1-100的所有数的和
#3. 输出 1-100 内的所有奇数
#4. 输出 1-100 内的所有偶数
#5. 求1-2+3-4+5 ... 99的所有数的和
#6. 用户登陆(三次机会重试)
#7:猜年龄游戏
要求:
允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
#8:猜年龄游戏升级版
要求:
允许用户最多尝试3
每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
如何猜对了,就直接退出
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#题一
count=1
while count <= 10:
if count == 7:
count+=1
continue
print(count)
count+=1


count=1
while count <= 10:
if count != 7:
print(count)
count+=1


#题目二
res=0
count=1
while count <= 100:
res+=count
count+=1
print(res)

#题目三
count=1
while count <= 100:
if count%2 != 0:
print(count)
count+=1

#题目四
count=1
while count <= 100:
if count%2 == 0:
print(count)
count+=1



#题目五
res=0
count=1
while count <= 5:
if count%2 == 0:
res-=count
else:
res+=count
count+=1
print(res)


#题目六
count=0
while count < 3:
name=input('请输入用户名:')
password=input('请输入密码:')
if name == 'egon' and password == '123':
print('login success')
break
else:
print('用户名或者密码错误')
count+=1

#题目七
age_of_oldboy=73

count=0
while count < 3:
guess=int(input('>>: '))
if guess == age_of_oldboy:
print('you got it')
break
count+=1

#题目八
age_of_oldboy=73

count=0
while True:
if count == 3:
choice=input('继续(Y/N?)>>: ')
if choice == 'Y' or choice == 'y':
count=0
else:
break

guess=int(input('>>: '))
if guess == age_of_oldboy:
print('you got it')
break
count+=1

for 循环

1、迭代式循环

1
2
3
# for语法如下
for i in 可迭代对象:
执行代码

补充:range函数 –> 用于生成一个区间范围的数字,左闭右开

1
2
for i in range(0,5):
print(i)

2、break与continue(同while)

3、循环嵌套

1
2
3
4
for i in range(1,10):
for j in range(1,i+1):
print('%s*%s=%s' %(i,j,i*j),end=' ')
print()
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
# for循环练习  打印金字塔
# 分析
'''

#max_level=5
* #current_level=1,空格数=4,*号数=1
*** #current_level=2,空格数=3,*号数=3
***** #current_level=3,空格数=2,*号数=5
******* #current_level=4,空格数=1,*号数=7
********* #current_level=5,空格数=0,*号数=9

#数学表达式
空格数=max_level-current_level
*号数=2*current_level-1

'''

# 实现
max_level=5
for current_level in range(1,max_level+1):
for i in range(max_level-current_level):
print(' ',end='') #在一行中连续打印多个空格
for j in range(2*current_level-1):
print('*',end='') #在一行中连续打印多个空格
print()

Python 流程控制
https://clark-cdc.github.io/2019/03/20/0004-流程控制/
作者
clark
发布于
2019年3月20日
许可协议