python 流程式控制制

來源:互聯網
上載者:User

標籤:python 流程式控制制

Python 用冒號: 作為程式塊標記關鍵字。
注意:每個用冒號‘:‘標記的程式塊內的代碼必須有相同的縮排

if/elif/else 判斷語句
[[email protected] opt]# cat test.py
#!/usr/bin/env python
# -- coding:utf-8 --

if name =="main":
print "Hello"
print "World"
[[email protected] opt]# ./test.py
Hello
World

Python中可以使用pass語句來定義範圍,但不做任何操作
# -- coding:utf-8 --

if name =="main":
pass
技巧 : pass用於需要寫代碼,但實際什麼也不做的場合

判斷語句3種
if expression1:
block_for_Trueif 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
# -- coding:utf-8 --
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
sys.argv 是一個系統List變數,sys.argv[0]為程式名,從第二個(索引1)開始的其他元素為字串類型的控制台輸入參數。

迴圈語句
1.
while expression:
repeat_block
2.
for element in iteralbe:
repeat_block

  1. 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()

[[email protected] opt]# ./test.py
pop element out egg
pop element out orange
pop element out banana
pop element out apple
[[email protected] 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
[[email protected] 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)
[[email protected] opt]# ./test.py
13 =3
2
3 =6
33 =9
4
3 =12
53 =15
6
3 =18
73 =21
8
3 =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之下的語句在程式中處理例外的情況。

處理不同種類的例外
[[email protected] 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))

[[email protected] 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 流程式控制制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.