python基礎---流程控制
阿新 • • 發佈:2017-07-10
python循環
流程控制
1、if判斷
a.單分支
if 條件:
滿足條件後要執行的代碼
age_of_oldboy=50
if age_of_oldboy > 40:
print(‘too old,time to end‘)
輸出:
too old,time to end
b.雙分支
if 條件:
滿足條件執行代碼
else:
if條件不滿足就走這段
age_of_oldboy=50
if age_of_oldboy > 100:
print(‘too old,time to end‘)
else:
print(‘impossible‘)
輸出:
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‘)
輸出:
age is :90 #如果一個if或者elif成立,就不再往下判斷
2、whil循環
a.while語法
while 條件: #只有當while後面的條件成立時才會執行下面的代碼
執行代碼...
count=1
while count <= 3:
print(count)
count+=1
輸出:
1
2
3
練習:打印10內的偶數
count=0
while count <= 10:
if count % 2 == 0:
print(count)
count+=1
輸出:
0
2
4
6
8
10
while ...else 語句
當while 循環正常執行完,中間沒有被break 中止的話,就會執行else後面的語句
count=1
whilecount <= 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:
break #跳出本層循環
print(count)
count+=1
輸出:
1
2
3
4
5
6
7
8
9 #當count=10時,就跳出本層循環
例:continue
count=0
while count < 5:
if count == 3:
count+=1
continue
print(count)
count+=1
輸出:
0
1
2
4 #當count=3時,就跳出本次循環,不打印3,進入下一次循環
使用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
持續更新中。。。
本文出自 “lyndon” 博客,請務必保留此出處http://lyndon.blog.51cto.com/11474010/1946068
python基礎---流程控制