流程控制
一、流程控制之if
对事物进行判断
if可以与与elif,else组合使用
if elif else 同一级别配合使用的时候,只会指向一个代码块,
当满足if条件时,就不会执行elif else 的代码;当满足elif 条件,就会跳过if 条件的代码,也不会执行else 部分的代码;
当if elif 条件都不满足时,就会执行else部分的代码。
#if...else例子
height = 168 age = 18 is_pretty = True
if height == 168 and age ==18 and is_pretty: print('表白')else: print('打扰了')
练习
如果 成绩>=90,打印"优秀"
如果 成绩>=80 并且 成绩<90,打印"良好"
如果 成绩>=70 并且 成绩<80,打印"普通"
其他情况:打印"差"
成绩评判 score = input("your score: ") score = int(score) # 注意类型转换 if score >= 90: print('优秀') elif score >= 80 and score < 90: elif score >= 80: print('良好') elif score >= 70 and score < 80: elif score >= 70: print('普通') else: print('差')
height = 168 age = 18 is_pretty = True is_success = False if height == 168 and age ==18 and is_pretty: print('表白') if is_success: print('在一起') else: print('开个玩笑而已') else: print('打扰了')
二、流程控制之while
while 是循环条件
避免死循环
#死循环
while True:
print('1')
print('2')
while+break
break是终止本次循环
# name='egon'
# password='123'
# while True:
# inp_name=input('姓名:')
# inp_password=input('密码:')
# if inp_name ==name and inp_password ==password:
print('登陆成功')
# break
# else:
# print('用户名或密码错误')
while+continue
continue是跳出本次循环,进行下一次循环
#打印1,2,4,5
count=1 while count<=5: if count==3: count+=1 continue print(count) count+=1
name='egon' password='123' while True: inp_name=input('姓名:') inp_password=input('密码:') if inp_name ==name and inp_password ==password: while True: cmd=input('>>:') if cmd=='quit': break print('退出') else: print('用户名或密码错误') continue
三、流程控制之for循环
语法结构:
1.for 变量名 in 容器类型
print('变量名')
2.不依赖索引
l = [11,22,33,44,55,66] #n = 0 while n <6: print(l[n]) n += 1 #n = 0 while n < len(l): print(l[n]) n += 1 #for i in l: print(i)
3.用for 循环打印打印1~9
for i in range(1,10): print(i)
python3中的range 与python2中的xrang相同
python2中的range是一个列表
for i in range(1,10): for j in range(1,1+i): print('%s*%s=%s'%(i,j,i*j),end=' ') print(' ')