1.初識for循環
理論上for循環能做的事,while循環也能做,但是for循環在取值上更加簡潔
基本語法:
for 變量 in 可迭代對象:
...
每次循環時,將可迭代對象的元素賦值給變量
ps:for循環的循環次數取決於可迭代對象元素的個數,也叫取值循環
2.for循環基本使用
1.簡單for循環
需求:將列表[1,2,3]中的每一個元素打印出來
使用for循環:
lst = [1,2,3]
for i in lst:
print(i)
使用while循環:
lst = [1,2,3]
count = 0
while count <= 2:
print(lst[count])
count += 1
可以明顯看到for循環更加簡潔
2.for range的使用
range(start,end,step) 生成一個可迭代對象
start 起始數字
end 終止數字
step 步長
給一個數字,從0開始,給兩個,從第一個開始,給步長,每一次加的值爲步長
for i in range(3):
print(i) 結果爲:0,1,2
for i in range(1,5):
print(i) 結果爲:1,2,3,4
for i in range(1,10,2):
print(i) 結果爲:1,3,5,7,9
3.打破循環
與while循環相同,也是使用break(打破本層循環),continue(打破本次循環)
1.需求:讓用戶輸入賬號密碼,匹配則提示登錄成功,最多三次機會
name = "yhr"
password = "123"
for i in range(3):
name_input = input("請輸入用戶名:")
password_input = input("請輸入密碼:")
if name_input == name and password_input == password:
print("登陸成功")
break
2.需求:輸出1-10,遇見4跳過
for i in range(1,11):
if i == 4:
continue