流程控制python
1、if判断ide
a.单分支spa
if 条件:input
知足条件后要执行的代码cmd
age_of_oldboy=50 if age_of_oldboy > 40: print('too old,time to end')
b.双分支it
if 条件:class
知足条件执行代码变量
else:循环
if条件不知足就走这段语法
age_of_oldboy=50 if age_of_oldboy > 100: print('too old,time to end') else: print('impossible')
c.多分支
if 条件:
知足条件执行代码
elif 条件:
上面的条件不知足就走这个
elif 条件:
上面的条件不知足就走这个
elif 条件:
上面的条件不知足就走这个
else:
上面全部的条件不知足就走这段
age_of_oldboy=91 if age_of_oldboy > 100: print('too old,time to end') elif age_of_oldboy > 90: print('age is :90') elif age_of_oldboy > 80: print('age is 80') else: print('impossible')
2、whil循环
a.while语法
while 条件: #只有当while后面的条件成立时才会执行下面的代码
执行代码...
count=1 while count <= 3: print(count) count+=1
练习:打印10内的偶数
count=0 while count <= 10: if count % 2 == 0: print(count) count+=1
while ...else 语句
当while 循环正常执行完,中间没有被break 停止的话,就会执行else后面的语句
count=1 while count <= 3: if count == 4: break print(count) count+=1 else: #while没有被break打断的时候才执行else的子代码 print('=========>')
b.循环控制
break 用于彻底结束一个循环,跳出循环体执行循环后面的语句
continue 终止本次循环,接着还执行后面的循环,break则彻底终止循环
例:break
count=1 while count <= 100: if count == 10: #当count=10时,就跳出本层循环 break #跳出本层循环 print(count) count+=1
例:continue
count=0 while count < 5: if count == 3: count+=1 #当count=3时,就跳出本次循环,不打印3,进入下一次循环 continue #跳出本次循环 print(count) count+=1
使用continue实现打印10之内的偶数
count=0 while count <= 10: if count % 2 != 0: count+=1 continue print(count) count+=1
c.死循环
while 是只要后边条件成立(也就是条件结果为真)就一直执行
通常写死循环能够:
while True:
执行代码。。。
还有一种:(好处是可使用一个变量来控制整个循环)
tag=True
while tag:
执行代码。。。
whiletag:
执行代码。。。
count=0 tag=True while tag: if count > 2: print('too many tries') break user=input('user: ') password=input('password: ') if user == 'egon' and password == '123': print('login successful') while tag: cmd=input('>>: ') if cmd == 'q': tag=False continue print('exec %s' %cmd) else: print('login err') count+=1
持续更新中。。。