目錄
條件語句
?循環語句
for 循環
?while 循環
break
?continue
條件語句
Python提供了?if
、elif
、else
?來進行邏輯判斷。格式如下:
Pythonif 判斷條件1:
? ? 執行語句1...
elif 判斷條件2:
? ? 執行語句2...
elif 判斷條件3:
? ? 執行語句3...
else:
? ? 執行語句4...
?循環語句
Python 提供了 for 循環和 while 循環。
for 循環
for 循環可以遍歷任何序列,比如:字符串、集合。如下所示:
字符串:
>>>
>>> str = 'hello'
>>> for s in str: print(s)
...
h
e
l
l
o
集合:
>>> l = ['high','gg','test']
>>> for x in l: print(x)
...
high
gg
test
>>>
?while 循環
滿足條件時進行循環,不滿足條件時退出循環。如下所示:
>>> num = 1
>>> while num <= 5:
... ? ? print(num)
... ? ? num += 1
...
1
2
3
4
5
>>>
break
在 for 循環和 while 循環語句中,用來終止整個循環。如下所示:
>>> str = 'Python'
>>> for s in str:
... ? ? if s == 'o':
... ? ? ? ? break
... ? ? print(s)
...
P
y
t
h
>>>
?continue
用在 for 循環和 while 循環語句中,用來終止本次循環。如下所示:
>>> str = 'Python'
>>> for s in str:
... ? ? if s == 'o':
... ? ? ? ? continue
... ? ? print(s)
...
P
y
t
h
n
>>>