選擇結構
if語句
在python語言中,可以使用if語句實現:
if <boolean expression>:
<statement 1>
<statement 2>
...
if x > y:
temp = x
x = y
y = temp
if-else語句
if <boolean expression>:
<block of statements>
else:
<block of statements>
if x > y:
max = x
else:
max = y
三元操作符
A=X if * else Y
*結果爲True時,A=X,否則爲Y
x = 5 if True else 3
y = 5 if False else 3
# 結果
x = 5
y = 3
循環結構
for循環
for <variable> in range(<start>, <stop>):
<block of statements>
for x in range(2):
print(x)
# 結果
0
1
for循環遍歷系列對象
# 字符串
str = "asd"
for i in str:
print(i)
# 列表
lis = list(str)
for i in lis:
print(i)
# 元組
tup = tuple(str)
for i in tuple(str):
print(i)
# 字典
dic = {}.fromkeys(str, 2)
for i in dic:
print(i)
# 集合
se=set(str)
for i in se:
print(i)
while語句
while <boolean expression>:
<statement 1>
<statement 2>
...
while x < 10:
print("X=", x)
x += 1
break和continue
break的含義就是中斷循環,跳出整個循環體。
a = 0
while True:
a += 2
if a > 10:
break
print(a)
# 結果
12
continue的含義是跳過循環體中其後面的部分代碼,繼續循環。
a = 0
while a < 5:
a += 1
if a % 2 == 0:
continue
else:
print(a)
# 結果
1
3
5