Python 分支、循環語句
1.1 單分支語句
1.2 多分支語句
1.3 while循環
1.4 for循環
1.5 並行迭代
1.6 列表推導式
1.7 exec關鍵字
單分支語句:
a=10
b=20
if a>b:
print "a>b"
else:
print "a<b"
運行結果:
a<b
[Finished in 0.1s]
多分支語句:
num=99
if num>=90:
print "優良"
elif num>=70 and num <90:
print "良好"
elif num>=60 and num<70:
print "一般"
else:
print "差"
運行結果:
優良
[Finished in 0.1s]
while循環:
i=1
while i<=3:
print "i的值為:"+str(i)
i+=1
運行結果:
i的值為:1
i的值為:2
i的值為:3
[Finished in 0.2s]
for循環:
list_a=['a','b','c']
for i in list_a:
print i
運行結果:
a
b
c
[Finished in 0.2s]
for循環取字典的鍵-值:
color={'blue':22,'green':33,'black':44,'White':55}
print color.items()
for key,value in color.items():
print key+" -->> "+str(value)
運行結果:
[('blue', 22), ('black', 44), ('White', 55), ('green', 33)]
blue -->> 22
black -->> 44
White -->> 55
green -->> 33
[Finished in 0.2s]
並行迭代zip():
a=[1,2,3,4]
b=['a','b','c']
print zip(b,a) #數字4丟失,因為b的長度比a的短
運行結果:
[('a', 1), ('b', 2), ('c', 3)]
[Finished in 0.2s]
列表推導式:
result=[i*i for i in range(3)]
print result
運行結果:
[0, 1, 4]
[Finished in 0.1s]
exec的使用:
exec關鍵字,可以用於執行一系列Python語句
list_a=[1,2,3,4]
exec 'print list_a' #使用exec執行Python語句
運行結果:
[1, 2, 3, 4]
[Finished in 0.2s]
