流程控制
一if循环
1. if判断
sex = 'female' age = 20 weight = 50 if age > 18 and age < 22 and sex == 'female' and weight == 50: print('你好')
2.if+else
sex = 'female' age = 20 weight = 50 if age > 18 and age < 22 and sex == 'female' and weight == 50: print('你好') else: print('再见')
3..if嵌套
sex = 'female' age = 20 weight = 50 is_successful=True if age > 18 and age < 22 and sex == 'female' \ and weight == 50: print('你好') if is_successful: print('了解一下') else: print('什么爱情') else: print('再见')
4.if+elif
如果:成绩>=90,那么:优秀 如果成绩>=80且<90,那么:良好 如果成绩>=70且<80,那么:普通 其他情况:很差 score = input('请输入你的分数:') score = int(score) if score >= 90: print('优秀') elif score >= 80: print('良好') elif score >= 70: print('普通') else: print('很差')
二while
while循环由又之为while条件循环
while True: name = input('please input you name:') pwd = input('please input you password:') if name == 'egon' and pwd == '123': print(' login successful') else: print('name or password error')
while条件改变
tag = True while tag: name = input('please input you name:') pwd = input('please input you password:') if name == 'egon' and pwd == '123': print('login succesful') tag = False else: print('name or password error') print('=====>')
while+break
退出本层(结束整个)循环
while True: name = input('please input you name:') pwd = input('please input you password:') if name == 'egon' and pwd == '123': print('login succesful') break else: print('name or password error') print('=====>')
while+continue
退出本次(单次)循环
while count<6: if count==4: count+=1 continue print(count) count+=1
while+else
当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句 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 ------
三for循环
1 迭代式循环:for,语法如下
for i in range(10):
缩进的代码块
2 break与continue(同上)
3 循环嵌套
for i in range(1,3): for j in range(1,4): print(i,j) 1 1 1 2 1 3 2 1 2 2 2 3
for i in range(1,10): for j in range(1,i+1): print('%s*%s=%s' %(j,i,i*j),end=' ') print() 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
4 range():
for i in range(10): print(i) 0 1 2 3 4 5 6 7 8 9
注意: python2中:range(1,5)直接生成[1,2,3,4]列表
python3中:range(1,5)不会直接生成列表,依旧是 range(1,5)