python 流程控制
註意:每個用冒號‘:‘標記的程序塊內的代碼必須有相同的縮進
if/elif/else 判斷語句
[root@SN28 opt]# cat test.py
#!/usr/bin/env python
# -- coding:utf-8 --
if name =="main":
print "Hello"
print "World"
[root@SN28 opt]# ./test.py
Hello
World
Python中可以使用pass語句來定義作用域,但不做任何操作
# -- coding:utf-8 --
if name
pass
技巧 : pass用於需要寫代碼,但實際什麽也不做的場合
判斷語句3種
if expression1:
block_for_True
if expression1:
block_for_True
else:
block_for_False
if expression1:
block_for_expression1
elif expression2:
block_for_expression2
....
elif expression3:
block_for_expression3
else:
block_for_False
實例:
#!/usr/bin/env python
import sys
param=None
if len(sys.argv) > 1:
param=int(sys.argv[1])
if param is None:
print "Alert"
print "please input a number."
elif param < -10:
print ‘too small‘
elif param > 10:
print ‘too big‘
else:
print "so good"
註意: None 可以”=“賦值None,在條件判斷中 用 is None
循環語句
1.
while expression:
repeat_block
2.
for element in iteralbe:
repeat_block
- break continue
實例:列表pop()動態刪除元素,len()動態判斷列表元素個數
#!/usr/bin/env python
# -- coding:utf-8 --
fruits=[‘apple‘,‘banana‘,‘orange‘,‘egg‘]
while len(fruits)>0:
print "pop element out",fruits.pop()
[root@SN28 opt]# ./test.py
pop element out egg
pop element out orange
pop element out banana
pop element out apple
[root@SN28 opt]#
#!/usr/bin/env python
# -- coding:utf8 --
import random
while True:
x=random.randint(1,6)
print (x)
if x==6:break
註釋:True:用於死循環。 break 退出循環
列表
#!/usr/bin/env python
# -- coding:utf-8 --
myList=[‘Englis‘,‘chinese‘,‘Japanese‘,‘German‘,‘France‘]
for element in myList:
print "current language is ",element
[root@SN28 opt]# ./test.py
current language is Englis
current language is chinese
current language is Japanese
current language is German
current language is France
-----------等同以下效果-------------------
#!/usr/bin/env python
# -- coding:utf-8 --
myList=[‘Englis‘,‘chinese‘,‘Japanese‘,‘German‘,‘France‘]
i=0
for element in myList:
print "current language is ",i,myList[i]
i=i+1
#!/usr/bin/env python
# -- coding:utf-8 --
myList=[‘Englis‘,‘chinese‘,‘Japanese‘,‘German‘,‘France‘]
for i,element in enumerate(myList):
print "current language is ",i,myList[i]
#!/usr/bin/env python
# -- coding:utf-8 --
def pick(x):
myList=[‘Englis‘,‘chinese‘,‘Japanese‘,‘German‘,‘France‘]
return myList[x]
alist=[0,1,2,3,4]
choices=map(pick,alist)
for choice in choices:
print choice
解釋:
map(執行用的函數,容器變量)
此函數會自動把每一個在容器變量中的元素都讀去出來,放到執行用函數中當作參數,在把返回值合並到一個容器變量中。
map函數中設置pick和alist,它把alist中的每一個數值都放入pick中執行,在搜集pick所返回來的每一個值,最後都放到choices容器變量中
實例
#!/usr/bin/env python
# -- coding:utf8 --
alist=range(1,9)
y=map(lambda x:x3,alist)
for i,element in enumerate(y,1):
print "{}3 ={}".format(i,element)
[root@localhost opt]# ./test.py
13 =3
23 =6
33 =9
43 =12
53 =15
63 =18
73 =21
83 =24
叠代器 enumerate map filter
例外處理
在處理數據時,經常遇到例外,使程序產生錯誤信息並突然中斷程序執行。把例外都攔截下來,加以處理,就是所謂的例外處理
#!/usr/bin/env python
# -- coding:utf8 --
while True:
try:
age=int(input("Please input age:"))
break
except:
print "please enter a number"
if age < 15:
print ‘you are too yong‘
凡是在try之內的語句只要有任何異常,程序控制流程就會自動跑到except之下的語句在程序中處理例外的情況。
處理不同種類的例外
[root@localhost opt]# cat test.py
#!/usr/bin/env python
# -- coding:utf8 --
import os,sys
try:
os.remove(‘filename‘)
except Exception as e:
print(e)
e_type,e_value,e_tb=sys.exc_info()
print("種類:{}\n消息:{}\n信息:{}".format(e_type,e_value,e_tb))
[root@localhost opt]# ./test.py
[Errno 2] No such file or directory: ‘filename‘
種類:<type ‘exceptions.OSError‘>
消息:[Errno 2] No such file or directory: ‘filename‘
信息:<traceback object at 0x7f9d99c6fb00>
說明:需要導入os,sys
先通過Exception 來捕捉所有的例外,並把例外事件以e當作是記錄的對象,使用print(e)把例外的信息打印出來。
python 流程控制