1. 程式人生 > >Python學習筆記(3)for循環和while循環

Python學習筆記(3)for循環和while循環

循環語句 con while循環 art start 開始 count als 一輪

2019-02-25

(1)break語句:終止當前循環,跳出循環體。

(2)continue語句:終止本輪循環並開始下一輪循環(在下一輪循環開始前,會先測試循環條件)。

(3)for循環

  ① range()函數:

    1) 語法:rang([start,]stop[,step = ?]) 表示從start參數的值開始,到stop參數的值結束,step= ?表示步長。

    2) range(3),生成0~2之間的所有的數字。

  ② for後面可以加else

  測試代碼

exit_flag = False
for i in range(10):
    
if i < 5: continue print("外層循環:",i) for j in range(10): if j == 5: exit_flag = True break print("內層循環:",j) if exit_flag == True: break

  運行結果:

外層循環: 5
內層循環: 0
內層循環: 1
內層循環: 2
內層循環: 3
內層循環: 4

(4)while循環

  ① 語法

while 條件:

        循環體

  當條件為真時,執行循環語句,否則退出循環。

  測試代碼:

_age = 22
counter = 0
while counter < 3:
user_age = int(input("user_age:"))
if _age == user_age:
print("you are right!!!")
break
else:
print("you are wrong!!!")
counter +=1
else:
print("you shouldn‘t input")

  運行結果:

user_age:22
you are right!!!
user_age:33
you are wrong!!!
user_age:34
you are wrong!!!
user_age:35
you are wrong!!!
you shouldnt input

Python學習筆記(3)for循環和while循環