1. 程式人生 > >Python——while、break、continue、else

Python——while、break、continue、else

ESS true -o 提示 python big you ger pass

1.while循環語句:

1  count = 0
2 while count <= 100:
3      print("loop ", count)
4      count += 1
5 print(----loop is ended----)

2.打印偶數:

 1 # 打印偶數
 2 # count = 0
 3 #
 4 # while count <= 100:
 5 #
 6 #     if count % 2 == 0: #偶數
 7 #         print("loop ", count)
 8 #
 9 #     count += 1
10 #
11 #
12
# print(‘----loop is ended----‘)

3.第50次不打印,第60-80打印對應值 的平方

 1 count = 0
 2 
 3 while count <= 100:
 4 
 5     if count == 50:
 6         pass #就是過。。
 7 
 8     elif count >= 60 and count <= 80:
 9         print(count*count)
10 
11     else:
12         print(loop , count)

count+=1

4.死循環

1 count = 0
2 
3 while True:
4     print("forever 21 ",count)
5     count += 1

5.循環終止語句:break&continue

break:用於完全結束一個循環,跳出循環體執行循環後面的語句

continue:不會跳出整個循環,終止本次循環,接著執行下次循環,break終止整個循環

1 # break 循環
2 # count=0
3 # while count<=100:
4 #     print(‘loop‘,count)
5 #     if count==5:
6 #         break
7 # count+=1 8 # print(‘-----out of while loop---‘)

1 #continue 循環
2 count=0
3 while count<=100:
4     print(loop,count)
5     if count==5:
6         continue
7     count+=1
8 # print(‘-----out of while loop---‘)   #一直打印5
9 #continue 跳出本次循環,不會執行count+=1,count一直為5

例1:讓用戶猜年齡

1 age = 26
2 user_guess = int(input("your guess:"))
3 if user_guess == age :
4     print("恭喜你答對了,可以抱得傻姑娘回家!")
5 elif user_guess < age :
6     print("try bigger")
7 else :
8     print("try smaller")

例2:用戶猜年齡升級版,讓用戶猜年齡,最多猜3次,中間猜對退出循環

 1 count = 0
 2 age = 26
 3 
 4 while count < 3:
 5 
 6     user_guess = int(input("your guess:"))
 7     if user_guess == age :
 8         print("恭喜你答對了,可以抱得傻姑娘回家!")
 9         break
10     elif user_guess < age :
11         print("try bigger")
12     else :
13         print("try smaller")
14 
15     count += 1

例3:用戶猜年齡繼續升級,讓用戶猜年齡,猜3次,如果用戶3次都錯,詢問用戶是否還想玩,如果為y,則繼續猜3次,以此往復【註解提示:相當於在count=3的時候詢問用戶,如果還想玩,等於把count變為0再從頭跑一遍】

count = 0
age = 26

while count < 3:

    user_guess = int(input("your guess:"))
    if user_guess == age :
        print("恭喜你答對了,可以抱得傻姑娘回家!")
        break
    elif user_guess < age :
        print("try bigger")
    else :
        print("try smaller")

    count += 1

    if count == 3:
        choice = input("你個笨蛋,沒猜對,還想繼續麽?(y|Y)")
        if choice == y or choice == Y:
            count = 0

6.while&else:while 後面的else的作用是,當while循環正常執行完,中間沒有被break中止的話,就會執行else後的語句【else 檢測你的循環過程有沒有中止過(當你的循環代碼比較長的時候)】

1  count=0
2 # while count <=5:
3 #     count+=1
4 #     print(‘loop‘,count)
5 #
6 # else:
7 #     print(‘循環正常執行完啦‘)
8 # print(‘-----out of while loop----‘)
1 count=0
2 while count<=5:
3     print(loop,count)
4     if count==3:
5         break
6     count+=1
7 else:
8     print(loop is done)

Python——while、break、continue、else