python流程式控制制

來源:互聯網
上載者:User

標籤:pytho   執行   traceback   導致   expr   raw   table   vim   href   

python流程式控制制條件
總結
迴圈
for迴圈
指令碼簡單使用
for典型1+…+100python指令碼
數列小細節
迭代遍曆
簡單操作
內嵌for迴圈經典-九九乘法表
for迴圈
常用關鍵字
猜隨機數
while
while與for相比
while迴圈
開啟檔案的方法
讀取檔案的方法
小結
for遍曆檔案的方法
小結:
總結
while迴圈
with+while迴圈
總結python流程式控制制條件
  • if文法
if expression:    # 運算式:    statement(s)    #  代碼塊 elif expression:    statement(s)else exdpression:    statement(s)

  

  • 分數判斷
    例如
[[email protected] day02]# cat 2.py #!/usr/bin/pythonscore = int(raw_input("Please input num: "))if score >= 90:    print ‘A‘    print ‘very good‘elif score >= 80:    print ‘B‘    print ‘good‘elif score >= 70:    print ‘C‘    print ‘pass‘else:    print ‘game over‘print ‘END‘

  

  • 操作
    效果
[[email protected] day02]# python 2.py Please input num: 2game overEND[[email protected] day02]# python 2.py Please input num: 70CpassEND[[email protected] day02]# python 2.py Please input num: 89BgoodEND[[email protected] day02]# python 2.py Please input num: 90Avery goodEND

  

  • 大寫字母與變成小寫方法
    例如
[[email protected] day02]# cat 4.py #!/usr/bin/pythonyn = raw_input("please input [YES/NO]: ")yn = yn.lower()    #用到一個字串的方法:大寫替換成小寫。與其相反的是.upperif yn == ‘y‘ or yn == ‘yes‘:    print "programe is runing…"elif yn == ‘n‘  or yn == ‘no‘:    print "programe is exit…"else:    print "please input [YES/NO]: "

  

  • 操作
    效果
[[email protected] day02]# python 4.py please input [YES/NO]: yprograme is runing…[[email protected] day02]# python 4.py please input [YES/NO]: yesprograme is runing…[[email protected] day02]# python 4.py please input [YES/NO]: nprograme is exit…[[email protected] day02]# python 4.py please input [YES/NO]: noprograme is exit…[[email protected] day02]# python 4.py please input [YES/NO]: aplease input [YES/NO]:

  

總結
除了shell之外,1返回的是正確,0返回的是錯誤。邏輯值(bool)包含了兩個值:True:表示非空的量(比如:string,tuple,list,set,dictonary),所有非零數。Fasle:表示0,None,空的量等。多條件判斷可以用and,or 等
迴圈
  • 迴圈是一個結構,導致程式要重複一定的次數。
  • 條件迴圈也是如此,當條件變為假,迴圈結束。
for迴圈
  • for迴圈:在序列裡,使用for迴圈遍曆。
  • 文法:
for iterating_var in sequence:  statement(s)

  

例如

In [4]: list1 = [1,2,3,4,5]In [5]: for i in list1:   …:     print i    …:     12345In [6]:  range(5)Out[6]: [0, 1, 2, 3, 4]In [7]: range(0,10,2)Out[7]: [0, 2, 4, 6, 8]In [8]: range(0,10,3)Out[8]: [0, 3, 6, 9]In [9]: for i in range(10):   …:     print i   …:     0123456789

  

指令碼簡單使用
[[email protected] day02]# cat 5.py #!/usr/bin/pythonfor i in range(1,11):    if i % 2 == 0:        print i[[email protected] day02]# vim 5.py[[email protected] day02]# python 5.py [2, 4, 6, 8, 10][[email protected] day02]# cat 5.py #!/usr/bin/pythonprint [i for i in range(1,11) if i % 2 == 0][[email protected] day02]# vim 5.py[[email protected] day02]# python 5.py [1, 9, 25, 49, 81][[email protected] day02]# cat 5.py #!/usr/bin/pythonprint [i**2 for i in range(1,11) if i % 2 != 0]

  

for典型1+…+100python指令碼
#!/usr/bin/pythonsum = 0for i in range(1,101):    sum = sum + i  # sum += iprint sum

  

數列小細節
range  佔用記憶體xrange  遍曆的時候才會佔用記憶體推薦使用xrange
迭代遍曆
  • 遍曆序列:將序列中各個元素取出來。
    -直接從序列取值
    -通過索引來取值
簡單操作
  • 通過迴圈的方法遍曆字典
    例如
In [11]: dict.fromkeys(‘abcde‘,100)   #利用dict.fromkeys方法建立字典Out[11]: {‘a‘: 100, ‘b‘: 100, ‘c‘: 100, ‘d‘: 100, ‘e‘: 100}In [12]: dic1 = dict.fromkeys(‘abcde‘,100)In [13]: dic1Out[13]: {‘a‘: 100, ‘b‘: 100, ‘c‘: 100, ‘d‘: 100, ‘e‘: 100}In [15]: for k in dic1:  #預設的情況下是取key    …:     print k    …:     acbedIn [16]: for k in dic1:                #通過索引取出value    …:     print k, dic1[k]    …:     a 100c 100b 100e 100d 100In [20]: for k in dic1:              #也可以通過預留位置,列印出想要的效果    …:     print "%s --> %s" % (k, dic1[k])    …:         a --> 100c --> 100b --> 100e --> 100d --> 100In [21]: for k in dic1:    …:     print "%s --> %s" % (k, dic1[k]),           #用,號可以抑制分行符號    …:         a --> 100 c --> 100 b --> 100 e --> 100 d --> 100In [24]: for k , v in dic1.items():print k ,v     #也可以通過itmes的方法取出key,valuea 100c 100b 100e 100d 100In [25]: for k, v in dic1.iteritems():print k, va 100c 100b 100e 100d 100

  

內嵌for迴圈經典-九九乘法表
  • 操作
[[email protected] day02]# cat 7.py #!/usr/bin/pythonfor i in xrange(1,10):                                      #乘法表不需要0,所以從1進行取值    for j in xrange(1,i+1):                                 #(1,3)就會從1,2進行取值,不包括3        print "%sx%s=%s" % (j, i, j*i),              #逗號抑制內部迴圈換行    print                                                           #內部迴圈結束進行換行輸出[[email protected] day02]# python 7.py1x1=11x2=2 2x2=41x3=3 2x3=6 3x3=91x4=4 2x4=8 3x4=12 4x4=161x5=5 2x5=10 3x5=15 4x5=20 5x5=251x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=361x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=491x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=641x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

  

for迴圈
  • for
  • else
  • for 迴圈如果正常結束,才會執行else語句。
常用關鍵字
breakcontinueexitpass

  

操作
例如

[[email protected] day02]# cat 8.py #!/usr/bin/pythonimport timeimport sysfor i in xrange(10):    if i == 5:        continue    elif i == 6:        pass    elif i < 9:        time.sleep(1)        print i    elif i == 9:        sys.exit(10)else:        print "EMD"print "hahaha"

  

猜隨機數
[[email protected] day02]# cat 10.py #!/usr/bin/env pythonimport randomright = random.randint(1,20)count = 0while count < 6:    num = input(‘please input a number:‘)    if num == right:print ‘you are right‘break    else:if num > right:print "binger than right"else:print "samller than right"    count += 1

  

whilewhile與for相比
  • for迴圈用在有次數的迴圈上。
  • while迴圈用在有條件的控制上。

    while迴圈
  • while迴圈,直到運算式變為假,才推出while迴圈,運算式是一個邏輯運算式,必須返回一個True或False。
  • 文法
while expression:    statement(s)

### 操作
例1

 [[email protected] day02]# cat 11.py #!/usr/bin/pythonn = 0while True:    if n == 10:        break    print  n , ‘hello‘    n += 1

  

輸出

[[email protected] day02]# python 11.py 0 hello1 hello2 hello3 hello4 hello5 hello6 hello7 hello8 hello9 hello

  

例2

[[email protected] day02]# cat 12.py #!/usr/bin/pythonwhile True:   string = raw_input(‘please input string: ‘)   if string == "q":        break

  

輸出

[[email protected] day02]# python 12.py please input string: eplease input string: wplease input string: q

  

例3

[[email protected] day02]# cat 13.py #!/usr/bin/pythonx = ‘‘while x != ‘q‘:    x = raw_input(‘please input: ‘ )

  

輸出

[[email protected] day02]# python 13.py please input: eplease input: wplease input: q

  

開啟檔案的方法

r: 以讀方式開啟
w: 以寫方式開啟
a: 以追加模式開啟
r+: 以讀寫入模式開啟
w+: 以讀寫入模式開啟
a+: 以讀寫入模式開啟
rb: 以二進位讀模式開啟
wb: 以二進位寫入模式開啟
ab: 以二進位追加模式開啟
rb+: 以二進位讀寫入模式開啟
wb+: 以二進位讀寫入模式開啟
ab+: 以二進位讀寫入模式開啟

  • 注意
    以w開啟檔案會覆蓋原來的檔案
讀取檔案的方法
In [31]: fd.             fd.close      fd.errors     fd.isatty     fd.newlines   fd.readinto   fd.seek       fd.truncate   fd.xreadlines              fd.closed     fd.fileno     fd.mode       fd.next       fd.readline   fd.softspace  fd.write                                 fd.encoding   fd.flush      fd.name       fd.read       fd.readlines  fd.tell       fd.writelines               In [30]: fd = open(‘/tmp/tmp.txt‘)In [31]: fd.read()Out[31]: ‘1\n2\n3\n‘In [32]: fd = open(‘/tmp/tmp.txt‘)In [33]: fd.readline()Out[33]: ‘1\n‘In [34]: fd.readline()Out[34]: ‘2\n‘In [35]: fd.readline()Out[35]: ‘3\n‘In [36]: fd.readline()Out[36]: ‘‘In [37]: fd = open(‘/tmp/tmp.txt‘)In [38]: fd.readlines()Out[38]: [‘1\n‘, ‘2\n‘, ‘3\n‘]In [39]: fd.readlines()Out[39]: []In [40]: fd = open(‘/tmp/tmp.txt‘)In [41]: fd.next()Out[41]: ‘1\n‘In [42]: fd.next()Out[42]: ‘2\n‘In [43]: fd.next()Out[43]: ‘3\n‘In [44]: fd.next()---------------------------------------------------------------------------StopIteration                             Traceback (most recent call last)<ipython-input-44-3df4eef70a28> in <module>()----> 1 fd.next()

  

小結
fd.read():返回的是字串fd.readline():返回的是每一行字串fd.readlines():返回的是一行列表
for遍曆檔案的方法
[[email protected] day02]# cat /tmp/tmp.txt123[[email protected] day02]# cat 14.py #!/usr/bin/pythonfd = open(‘/tmp/tmp.txt‘)for line in fd.readlines():    print line,[[email protected] day02]# python 14.py 123[[email protected] day02]# cat 14.py > 15.py[[email protected] day02]# vi 15.py [[email protected] day02]# cat 15.py #!/usr/bin/pythonfd = open(‘/tmp/tmp.txt‘)for line in fd:    print line,[[email protected] day02]# python 15.py 123

  

小結:
print line後面加個逗號,可以抑制print預設的換行。for line in fd.readlines(): 這種方法會全部加在到記憶體中,不建議使用for line in fd: 這種方法類似於fd.next(),沒迴圈一次加在一行,推薦使用。
總結
開啟檔案的時候要使用w方法會覆蓋原來的檔案,謹慎使用read(),readline()readlins()的區別是字串和列表使用方法的時候選擇最小消耗資源的方式
while迴圈
[[email protected] day02]# cat 16.py #!/usr/bin/pythonfd = open(‘/tmp/tmp.txt‘)while True:     line = fd.readline()    if not line:        break     print line,fd.close[[email protected] day02]# python 16.py 123

  

with+while迴圈
[[email protected] day02]# cat 17.py #!/usr/bin/pythonwith open(‘/tmp/tmp.txt‘) as fd:    while True:         line = fd.readline()        if not line:            break         print line,[[email protected] day02]# python 17.py123

  

總結
for迴圈有一定的次數while迴圈需要給出條件,條件陳述式後面要加:for和while遍曆完檔案之後需要加fd.close關閉檔案,養成好習慣,如果不加python執行完系統也會進行回收with+while進行迴圈就不用加close的方法

 

    

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.