for循環
像while循環一樣,for可以完成循環的功能。
在Python中 for循環可以遍歷任何序列的項目,如一個列表或者一個字符串等。
for循環的格式
for 臨時變量 in 列表或者字符串等可迭代對象:
循環滿足條件時執行的代碼
demo1
name = 'itheima'
for x in name:
print(x)
運行結果如下:
i
t
h
e
i
m
a
demo2
>>> for x in name:
print(x)
if x == 'l':
print("Hello world!")
運行結果如下:
h
e
l
Hello world!
l
Hello world!
o
demo3
# range(5) 在python就業班中進行講解會牽扯到迭代器的知識,
# 作爲剛開始學習python的我們,此階段僅僅知道range(5)表示可以循環5次即可
for i in range(5):
print(i)
'''
效果等同於 while 循環的:
i = 0
while i < 5:
print(i)
i += 1
'''
運行結果如下:
0
1
2
3
4
break和continue
1. break
<1> for循環
- 普通的循環示例如下:
name = 'itheima'
for x in name:
print('----')
print(x)
else:
print("==for循環過程中,如果沒有執行break退出,則執行本語句==")
運行結果:
----
i
----
t
----
h
----
e
----
i
----
m
----
a
==for循環過程中,如果沒有break則執行==
- 帶有break的循環示例如下:
name = 'itheima'
for x in name:
print('----')
if x == 'e':
break
print(x)
else:
print("==for循環過程中,如果沒有執行break退出,則執行本語句==")
運行結果:
----
i
----
t
----
h
----
<2> while循環
- 普通的循環示例如下:
i = 0
while i<5:
i = i+1
print('----')
print(i)
else:
print("==while循環過程中,如果沒有執行break退出,則執行本語句==")
運行結果:
----
1
----
2
----
3
----
4
----
5
==while循環過程中,如果沒有break則執行==
- 帶有break的循環示例如下:
i = 0
while i<5:
i = i+1
print('----')
if i==3:
break
print(i)
else:
print("==while循環過程中,如果沒有執行break退出,則執行本語句==")
運行結果:
----
1
----
2
----
小結:
- break的作用:立刻結束break所在的循環
2. continue
<1> for循環
- 帶有continue的循環示例如下:
name = 'itheima'
for x in name:
print('----')
if x == 'e':
continue
print(x)
else:
print("==while循環過程中,如果沒有break則執行==")
運行結果:
----
i
----
t
----
h
----
----
i
----
m
----
a
==while循環過程中,如果沒有break則執行==
<2> while循環
- 帶有continue的循環示例如下:
i = 0
while i<5:
i = i+1
print('----')
if i==3:
continue
print(i)
運行結果:
----
1
----
2
----
----
4
----
5
小結:
- continue的作用:用來結束本次循環,緊接着執行下一次的循環
3. 注意點
break/continue只能用在循環中,除此以外不能單獨使用
break/continue在嵌套循環中,只對最近的一層循環起作用