第三篇 流程控制
第三篇 流程控制
#一、判断语句
1 if语句
格式:
if 条件: 代码块
如果条件成立,则执行代码块中的内容
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
2 if...else...语句
格式:
if 条件: 代码块A else: 代码块B
如果条件成立,则执行代码块A中的内容,否则,执行代码块B中的内容
3 if...elif...else...
格式:
if 条件1: 代码块A elif 条件2: 代码块B else: 代码块C
如果条件1成立,则执行代码块A中的内容,否则转而判断下一行条件(条件2),若条件2成立,则执行代码块B中的内容,如果条件2也不成立,则执行代码块C
注意:==代码块A、代码块B和代码块C中只可能有一个代码块会被执行==
4 if语句的嵌套使用
例如:
age = 20 gender = 'female' result = True if age <= 26 and age >= 20 and gender == 'female': print('表白') if result: print('HAHA') else: print('sorry,goodbye') else: print('hello')
结果是
表白
HAHA
5 练习
- 成绩评定:如果成绩大于等于90,打印“优秀”
如果成绩大于等于80,打印“良好”
如果成绩大于等于60,打印“合格”
其他情况,打印“差”
score = input("your score:")
score = int(score)
#利用逆向思维可以写出更简洁的代码,如下面所示
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elsif score >= 60:
print('及格')
else:
print('差')
'''
注意:由于计算机是从上往下执行的,所以不能把判断范围小的条件放在前面,如果
把判断范围小的条件放在前面,逻辑上会有错误
'''
- 模拟登陆注册
user_name = 'king'
user_password = '666'
inp_user_name = input("Please enter your user name:")
inp_user_password = input("Please enter user password:")
if inp_user_name == user_name and inp_user_password == user_password:
print('login successful')
else:
print('username or password error')
结果是:Please enter your user name:king
Please enter user password:666
login successful
#二、 循环语句
1 while循环
- 格式:
while 条件:
代码块
- 实现可以重复输入的模拟登陆
while True:
user_name = 'king'
user_password = '666'
inp_user_name = input("Please enter your user name:")
inp_user_password = input("Please enter user password:")
if inp_user_name == user_name and inp_user_password == user_password:
print('login successful')
else:
print('username or password error')
无论输入是否正确,都会一直循环,用户可以一直输入
我们可以在while循环中嵌套break,使用户的输入是有限次数的,且当输入正确时,程序也会终止
#给用户输入的次数,我们可以自行设定
fixed_count = 3
count = 0
while count < fixed_count:
user_name = 'king'
user_password = '666'
inp_user_name = input("Please enter your user name:")
inp_user_password = input("Please enter user password:")
if inp_user_name == user_name and inp_user_password == user_password:
print('login successful')
break
else:
print('username or password error')
count += 1
这样用户只有3次输入的机会,而当用户输入正确时,程序也会立即终止
2 for循环
- 为什么有while循环还需要for循环呢?在python中,当需要取出字典中的多个值时,while就有点力不从心了,而for可以很方便的取出字典中的key
info = {'name':'king','age':26}
for item in info:
print(item) #取出的是info的key(关键字)
执行结果是:
name
age
Process finished with exit code 0
- for循环的循环次数受限于容器类型的长度,而while循环的循环次数需要自己控制。for循环也可以按照索引取值。
for i in range(0,3): #range顾头不顾尾
print(i,end = ' ')
打印结果是:0 1 2
- for循环按照索引取出列表中的值
name_list = ['king','tom','bob','jack']
for i in range(len(name_list)):
print(f'name_list[{i}]={name_list[i]}')
执行结果是:
name_list[0]=king
name_list[1]=tom
name_list[2]=bob
name_list[3]=jack
Process finished with exit code 0
3 while循环的嵌套
- 不要想着一蹴而就,一个程序的编写一般都会经历修修改改,我们在编写程序时,不要想着一开始就完美,而是先准确地把功能一步一步实现
- 假如有一个登陆系统,登陆之后可以有很多功能,当我们使用完功能后想退出系统,我们如何退出呢,下面我们来一步一步实现
退出内层循环
while True:
raw_data_name = 'king' #raw data 是原始数据的意思
raw_data_password = '666'
inp_name = input('username:')
inp_password = input('userpassword:')
if inp_name == raw_data_name and inp_password == raw_data_password:
print('login successful') #登陆成功的意思
while True:
cmd = input('Please input the command you want') '''command就是cmd,命令的意思'''
if cmd == 'q': #quit是离开的意思
break
print(f'{cmd} 功能执行...')
else:
print('username or password error')
print('退出系统') #这行代码不在整个循环中,只有当整个循环全部结束才会执行
当用户进入系统之后并输入q时,只能退出第二个while循环(内层的while循环),然后程序又会进入第一个while循环
执行结果:username:king
userpassword:666
login successful
Please input the command you want:q
username:
退出外层循环
while True:
raw_data_name = 'king' #raw data 是原始数据的意思
raw_data_password = '666'
inp_name = input('username:')
inp_password = input('userpassword:')
if inp_name == raw_data_name and inp_password == raw_data_password:
print('login successful') #登陆成功的意思
while True:
cmd = input('Please input the command you want') '''command就是cmd,命令的意思'''
if cmd == 'q': #quit是离开的意思
break
print(f'{cmd} 功能执行...')
break #这个break可以结束外层while循环
else:
print('username or password error')
print('退出系统')
执行结果是:username:king
userpassword:666
login successful
Please input the command you want:q
退出系统
Process finished with exit code 0
4 for循环的嵌套
- for循环执行规律:外层循环循环一次,内层循环循环所有的
for i in range(2):
print(f'xxxx,i={i}')
for j in range(2):
print(f'oooo,j={j}')
执行结果是:
xxxx,i=0
oooo,j=0
oooo,j=1
xxxx,i=1
oooo,j=0
oooo,j=1
Process finished with exit code 0
5 tag控制while循环退出
- 相当于利用一个变量tag来控制while循环的判断条件是否为True
tag = True
while tag:
raw_data_name = 'king' #raw data 是原始数据的意思
raw_data_password = '666'
inp_name = input('username:')
inp_password = input('userpassword:')
if inp_name == raw_data_name and inp_password == raw_data_password:
print('login successful') #登陆成功的意思
while True:
cmd = input('Please input the command you want') '''command就是cmd,命令的意思'''
if cmd == 'q': #quit是离开的意思
tag = False
print(f'{cmd} 功能执行...')
else:
print('username or password error')
print('退出系统') #这行代码不在整个循环中,只有当整个循环全部结束才会执行
执行结果是:username:king
userpassword:666
login successful
Please input the command you want:q
q 功能执行...
退出系统
Process finished with exit code 0
6 while...else...
- 只有当while没有被break时才会执行else中的代码
n = 0
while n < 1:
print(n)
n += 1
else:
print('while没有被break')
执行结果:0
while没有被break
Process finished with exit code 0
- 如果给上述的程序中,while循环里面嵌套一个break,则else中的代码不会执行
n = 0
while n < 1:
print(n)
n += 1
break
else:
print('while没有被break')
执行结果是:0
Process finished with exit code 0
7 for循环实现loading...
import time
print('loading',end = '')
for i in range(6):
print('.',end = '')
time.sleep(0.5)
#三、break和continue
1 break
- break是用来终止循环的,一般和if判断语句配合在循环语句中使用,在C语言中,break也可以用来终止switch判断语句
- break和while循环的嵌套使用可以在上述的while循环中理解
- break与for循环的嵌套使用
name_list = ['king','tom','bob','jack']
for i in name_list:
if i == 'bob':
break
print(i)
输出的结果是:king
tom
2 continue
- continue的意思是终止本次循环,直接进入下一次循环
- while循环和continue的嵌套使用
n = 0
while n < 9:
if n == 6:
n += 1 '''注意:如果注释这一行,pycharm虽然不会报错,但是逻辑上程序已经进入死循环'''
continue
print(n,end=' ')
n += 1
运行结果是: 0 1 2 3 4 5 7 8
- for循环和continue的嵌套使用,和while相似也需要配合if来实现
name_list = ['king','tom','bob','jack']
for i in name_list:
if i == 'bob':
continue
print(i,end = ' ')
运行结果是:king tom jack
#四、练习
1 用for循环写一个9x9乘法表
for i in range(1,10): #外层循环控制行数:1到9,共9行
for j in range(1,i+1): #内存循环控制列数:1到i,所以列数与行数相等
print(f'{i}*{j}={i*j}',end = ' ')
print()
执行结果(略)
2 用for循环写一个金字塔
row = 5 #row是行的意思,column是列的意思
for i in range(row):
star_cnt = 2*i-1
space_cnt = row - i
print(f'{" "*space_cnt}{"*"*star_cnt}')
'''一定要牢记占位符的作用,{}里面的值需要自己完全理解并掌握,比如上述的{" "*space_cnt}表示:先将 “空格” 乘以 “空格个数” 之后再进行输出'''
执行结果(略)
