day04-流程控制
目录:
一、流程控制之if...else
1.1 为什么需要if...else的流程控制?
#人脑无非是数学运算和逻辑运算,数学运算就是加减乘除之类的,这里我们主要研究逻辑运算,即人根据外部条件的变化而做出不同的反映,比如,那么它必须也要具备判断事物对错的能力,从而作出不同的响应。
#比如面前走过一个妹纸,你会想好不好看,要不要超过去看看正脸?或者程序中比如ATM取款机,需要接收你输入的用户名和密码来判断你是否是合法用户等等。
#我们想要计算机像人一样去工作,就需要模拟人对某些事物的判断并作出不同的决策,这就需要程序中有相应的机制去模拟。
1.2 怎么用if...else?
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
if 条件:
代码1
代码2
代码3
...
# 代码块(同一缩进级别的代码,例如代码1、代码2和代码3是相同缩进的代码,这三个代码组合在一起就是一个代码块,相同缩进的代码会自上而下的运行)
比如你眼前走过了一个生物,你的大脑会迅速的采集这些信息然后判断是不是女人,年龄在18到24之间,长是否好看等,映射到计算机上就是比对一堆变量
cls = 'human'
gender = 'female'
age = 24
if cls == 'human' and gender == 'female' and age > 28 and age < 28:
print('开始表白')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
if 条件:
代码1
代码2
代码3
...
else:
代码1
代码2
代码3
...
if...else表示if成立代码成立会干什么,else不成立会干什么。
cls = 'human'
gender = 'female'
age = 38
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
else:
print('阿姨好')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
if 条件1:
代码1
代码2
代码3
...
elif 条件3:
代码1
代码2
代码3
...
...
else:
代码1
代码2
代码3
...
if...elif...else表示if条件1成立干什么,elif条件2成立干什么,elif条件3成立干什么,elif...否则干什么。
cls = 'human'
gender = 'female'
age = 28
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
print('考虑下')
else:
print('阿姨好')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#在表白的基础上继续:
#如果表白成功,那么:在一起
#否则:打印。。。
age_of_girl=18
height=171
weight=99
is_pretty=True
success=False
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
if success:
print('表白成功,在一起')
else:
print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
print('阿姨好')
练习:成绩评判
* 如果 成绩>=90,打印"优秀"
* 如果 成绩>=80 并且 成绩<90,打印"良好"
* 如果 成绩>=70 并且 成绩<80,打印"普通"
* 其他情况:打印"差"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
score=input('>>: ')
score=int(score)
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 70:
print('普通')
else:
print('很差')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
name=input('请输入用户名字:')
password=input('请输入密码:')
if name == 'Ryan' and password == '123':
print('Ryan login success')
else:
print('用户名或密码错误')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
'''
Ryan --> 超级管理员
Tom --> 普通管理员
Jack,Rain --> 业务主管
其他 --> 普通用户
'''
name=input('请输入用户名字:')
if name == 'Ryan':
print('超级管理员')
elif name == 'Tom':
print('普通管理员')
elif name == 'Jack' or name == 'Rain':
print('业务主管')
else:
print('普通用户')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 如果:今天是Monday,那么:上班
# 如果:今天是Tuesday,那么:上班
# 如果:今天是Wednesday,那么:上班
# 如果:今天是Thursday,那么:上班
# 如果:今天是Friday,那么:上班
# 如果:今天是Saturday,那么:出去浪
# 如果:今天是Sunday,那么:出去浪
#方式一:
today=input('>>: ')
if today == 'Monday':
print('上班')
elif today == 'Tuesday':
print('上班')
elif today == 'Wednesday':
print('上班')
elif today == 'Thursday':
print('上班')
elif today == 'Friday':
print('上班')
elif today == 'Saturday':
print('出去浪')
elif today == 'Sunday':
print('出去浪')
else:
print('''必须输入其中一种:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
''')
#方式二:
today=input('>>: ')
if today == 'Saturday' or today == 'Sunday':
print('出去浪')
elif today == 'Monday' or today == 'Tuesday' or today == 'Wednesday' \
or today == 'Thursday' or today == 'Friday':
print('上班')
else:
print('''必须输入其中一种:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
''')
#方式三:
today=input('>>: ')
if today in ['Saturday','Sunday']:
print('出去浪')
elif today in ['Monday','Tuesday','Wednesday','Thursday','Friday']:
print('上班')
else:
print('''必须输入其中一种:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
''')
二、流程控制之while循环
2.1 为何要用while循环
#实际生活中类似于重复的做一些事情,流水线上的工人反复劳动,直到下班时间到来
#程序中需不需要做重复的事情呢?以刚刚的验证用户名和密码的例子为例,用户无论输入对错,程序都会立马结束,真正不应该是这个样子。。。
2.2 怎么使用while循环
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
while 条件: # 条件选择:True or False
code 1
code 2
code 3
...
# 循环体
# 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
# 如果条件为假,那么循环体不执行,循环终止
# 避免死循环
#打印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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
user_db = 'Ryan'
pwd_db = '123'
while True:
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
else:
print('username or password error')
#ps:用户输错了确实能够获取重新输,但用户输对了发现还需要输,这我就忍不了
2.3 死循环
import time
num=0
while True:
print('count',num)
time.sleep(1)
num+=1
2.4 break与continue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#break的意思是终止掉当前层的循环,执行其他代码。
while True:
print('1')
print('2')
break
print('3')
# 上面仅仅是演示break用法,实际不可能像我们这样去写,循环结束应该取决于条件
user_db = 'Ryan'
pwd_db = '123'
while True:
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
break
else:
print('username or password error')
print('退出了while循环')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
continue的意思是终止本次循环,直接进入下一次循环
while True:
if 条件1:
code1
code2
code3
...
continue # 无意义
elif 条件1:
code1
code2
code3
...
continue # 无意义
else:
code1
code2
code3
...
continue # 无意义
循环打印出1,2,3,4,5,6,7,8,9
n = 1
while n < 4:
print(n)
n += 1 # 这一行不加又会是死循环
```
变一下循环打印1,2,3,4,5,7,8,9,数字6不打印
n = 1
while n < 10:
if n == 6:
n += 1 # 如果注释这一行,则会进入死循环
continue
print(n)
n += 1
ps:continue不能加在最后一步执行的代码,因为代码加上去毫无意义
2.5 循环嵌套与tag
#ATM密码输入成功还需要进行一系列的命令操作,比如取款,比如转账。并且在执行功能结束后会退出命令操作的功能,即在功能出执行输入q会退出输出功能的while循环并且退出ATM程序。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
tag=True
while tag:
......
while tag:
........
while tag:
tag=False
# 退出内层循环的while循环嵌套
user_db = 'Ryan'
pwd_db = '123'
while True:
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('请输入你需要的命令:')
if cmd == 'q':
break
print('%s功能执行'%cmd)
else:
print('username or password error')
print('退出了while循环')
# 退出双层循环的while循环嵌套
user_db = 'Ryan'
pwd_db = '123'
while True:
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('请输入你需要的命令:')
if cmd == 'q':
break
print('%s功能执行'%cmd)
break
else:
print('username or password error')
print('退出了while循环')
上述方法有点low,有多个while循环就要写多个break,有没有一种方法能够帮我解决,只要我退出一层循环其余的各层全都跟着结束>>>:定义标志位
# 退出双层循环的while循环嵌套
user_db = 'Ryan'
pwd_db = '123'
flag = True
while flag:
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while flag:
cmd = input('请输入你需要的命令:')
if cmd == 'q':
flag = False
break
print('%s功能执行'%cmd)
else:
print('username or password error')
print('退出了while循环')
2.6 while+else
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
while...else:else会在while没有被break时才会执行else中的代码。
n = 1
while n < 3:
if n == 2:break # 不会走else
print(n)
n += 1
else:
print('else会在while没有被break时才会执行else中的代码')
2.7 while循环练习题
#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,就退出程序
如何猜对了,就直接退出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#题一
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循环
3.1 为什么需要for循环
#想要循环一个列表里面每一个元素,我们可以用while循环,但是想获取字典里面的多个值,用while循环就很难去实现,因为字典里的值没有顺序,这个时候就需要使用另外一种循环机制for循环:不依赖于索引取值
3.2 怎么使用for循环?
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for name in name_list: #迭代式循环
print(name) # 对比与while更加简便
例如:
for i in range(10):
print(i)
# 再来看for循环字典会得到什么
info = {'name': 'Ryan', 'age': 19}
for item in info:
print(item) # 拿到字典所有的key
print(info[item])
# for可以不依赖于索引取指,是一种通用的循环取指方式
# for的循环次数是由被循环对象包含值的个数决定的,而while的循环次数是由条件决定的
#for循环也可以按照索引取值
for i in range(1, 10): # range顾头不顾尾
print(i)
# python2与python3中range的区别(cmd窗口演示)
# for循环按照索引取值
name_list = ['jason', 'nick', 'tank', 'sean']
# for i in range(0,5): # 5是数的
for i in range(len(name_list)):
print(i, name_list[i])
3.3 break与continue
# for+break 跳出本层循环
name_list = ['Jenny', 'Richard', 'apri', 'Annie']
for name in name_list:
if name == 'apri':
break
print(name)
# for+continue 跳出本次循环,进入下一次循环
name_list = ['Jenny', 'Richard', 'apri', 'Annie']
for name in name_list:
if name == 'apri':
continue
print(name)
3.4 循环嵌套
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(1,10):
for j in range(1,i+1):
print('%s*%s=%s' %(i,j,i*j),end=' ')
print()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#分析
'''
#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()
for+else