python基礎---流程控制


流程控制python


1if判斷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')


2whil循環

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



持續更新中。。。

相關文章
相關標籤/搜索