一個「MacBook」新手的Python「笨辦法」自學之旅 #第十章預告:邏輯關係、布爾表達式、if/elif/else語句、循環for語句、while語句、列表及其相關

第十章預告:邏輯關係、布爾表達式、if/elif/else語句、循環for語句、while語句、列表及其相關python

 

   這一章,最關鍵的是分清TrueFalse。注意這兩個單詞的形式必須是:首字母大寫,其他小寫,由於只有這樣,Python纔會辨別。編程

 

 ---------------------------------<習題27&28:邏輯關係和布爾表達式>------------------------------app

   

   這兩個習題,講得就是咱們常說的「與或非」,經過一系列的運算,獲得一個True或者False。具體內容你們請參考Zed.A.Shaw著《「笨辦法」學Python》的習題27和習題28。less

   值得注意的是:若是在and 和 or 語句兩側,不是True或False,而是數值或字符串,Python會返回什麼樣的結果呢?dom

   下面是我在python裏嘗試的結果:ide

    

   其實上面截圖裏的命令行,不是布爾表達式,而是簡單的and和or語句(兩側都不是True或false)不知道你們有沒有總結出規律:函數

   1,or  語句,Python返回第一個操做對象;可是若是or語句兩側有一個False,Python返回另一個「非False」的對象,這個語句屬於布爾表達式oop

   2,and語句,Python返回第二個操做對象;可是若是and語句兩側有一個False,Python只返回False,這個語句屬於布爾表達式ui

 

   上面的結果,於Zed.A.Shaw在習題28的第一個常見問題的解答有部分衝突,感興趣的朋友能夠本身研究一下!this

 

--------------------------------<習題29&30&31:if/else/elif語句及其應用>-----------------------------

   

   稍微接觸過編程的同窗,應該都知道if語句,這是三個習題都比較容易閱讀和理解,我就很少介紹,只在這貼出代碼。

 1 #-*-coding:utf-8-*-
 2 # 簡單的if語句
 3 people = 3
 4 cats = 2
 5 dogs = 5
 6 
 7 
 8 if people < cats: #此處的冒號,是告訴python接下來要建立一個新的代碼塊
 9    print "Not many cats! The world is doomed!"
10    
11 if people > cats:
12    print "Not many cats! The world is saved!"
13    
14 if people < dogs:
15    print "The world is drooled on!"
16    
17 if people > dogs:
18    print "The world is dry!"
19    
20    
21 dogs += 5
22 
23 if people >= dogs:
24    print "People are greater than or equal to dogs."
25    
26 if people <= dogs:
27    print "People are less than or equal to dogs."
28    
29 
30 if people == dogs:
31    print "People are dogs."
32    
ex29.py
 1 #-*-coding:utf-8-*-
 2 # if/else語句,輸入值已經預約OK了
 3 people = 30
 4 cars = 40
 5 buses = 15
 6 
 7 
 8 if cars > people:
 9     print "We should take the cars."
10 elif cars <people:
11     print "We sholud not take the cars."
12 else:
13     print "We can't decide."
14 
15 if buses > cars:
16     print "That's too many buses."
17 elif buses < cars:
18     print "Maybe we could take the buses."
19 elif buses < people:  #python只會運行它遇到的是True的第一個elif語句,此處的爲第二個,全部python並不運行
20     print "ss"
21 else:
22     print "We still can't decide."
23     
24 if people > buses:
25     print "Alright, let's just take the buses"
26 else:
27     print "Fine, let's stay home then."
ex30.py
 1 #-*-coding:utf-8-*-
 2 # if/else語句:輸入值是用戶本身輸入,即用戶本身作出決定
 3 print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
 4 
 5 door = raw_input(">")
 6 
 7 if door =="1":
 8     print "***There's a giant bear here eating a cheese cake. What do you do?***"
 9     print "(1) Take the cake."
10     print "(2) Scream at the bear."
11     
12     bear = raw_input(">")
13     
14     if bear == "1":
15         print "The bear eats your face off. Good job!"
16     elif bear == "2":
17         print "The bear eats your legs off. Good job!"
18     else:
19         print "Well, doing %s is probably better. Bear runs away."% bear
20 
21 elif door =="2":
22     print "***You stare into the endless abyss at Cthulhu's retina***"
23     print "(1) Blueberries."
24     print "(2) Yellow jacket clothespins."
25     print "(3) Understanding revolvers yelling melodies."
26     
27     insanity = raw_input(">")
28     
29     if insanity == "1" or insanity =="2":
30         print "Your body survives powered by a mind of jello. Good job!"
31     else:
32         print "The insanity rots your eyes into a pool of muck. Good job!"
33         
34 else:
35     print "You stumble around and fall on a knife and die. Good job!"
36     
ex31.py

   須要強調一下elif語句:它至關於if語句的擴展,能夠存在多個elif語句,並且若是它們都是True,python只會運行它遇到的第一個True的if或elif語句。可參考ex30.py

   關於if,elif,else語句的運行順序和原理,我作了一個代碼以下:

 1 #-*-coding:utf-8-*-
 2 # 區別if/else 和if/elif/else的區別
 3 prompt = "<"
 4 a=int(raw_input(prompt)) #此處必須將a強制轉換成數字型字符,否則下方只運行else命令
 5 b=int(raw_input(prompt))
 6 
 7 
 8 print "This is if and else"
 9 if a < 7:
10     print "A"
11 if a < 8:
12     print "B"
13 if a < 9:
14     print "C"
15 if b <12:
16     print "D"
17 else:
18     print "X"
19 
20 print "This is if and elif and else"
21 if a < 7:
22     print "E"
23 elif a < 8:
24     print "F"
25 elif a < 9:
26     print "G"
27 elif b < 12:
28     print "H"
29 else: 
30     print "Y"
ex31_1.py

 

-----------------------------------<習題32:for循環語句和列表list>--------------------------------

   

   從這個習題開始,寫的代碼都稍微有些複雜了,特別是牽扯到列表list。沒關係張,換種說法:如今你應該有能力寫出更有趣的程序啦!

   單詞for在英語中的解釋,也有「由於、因爲」的意思,那麼for循環語句就能夠這麼解釋:因爲xxxxx,而xxxxx。

   列表list:這是一個很重要的東西,但願你們給予足夠的尊重!

   列表的形式: list = ['brown', 'blond', 'red'] 表示該列表被賦值給一個叫list的變量,該列表含有三個元素,分別是'brown', 'blond', 'red',若是須要調用這三個元素,能夠用list[0], list[1], list[2]。 其實列表的最後一個元素,也能夠用list[-1]來調用,記住第一個元素是list[0]。

   列表的元素能夠是:數值、字符串、甚至也能夠是列表

 

   ex32.py:簡單介紹列表list是什麼; 如何用for循環打印列表的元素;如何append在空列表裏添加元素,代碼以下:

 1 #-*-coding:utf-8-*-
 2 # for循環和列表:打印列表,建立列表,在列表中增長數字
 3 the_count = [1, 2, 3, 4, 5]
 4 fruits = ['apples', 'oranges', 'pears', 'apricots']
 5 change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
 6 
 7 # this first kind of for~loop goes through a list
 8 for number in the_count:
 9     print "This is count %d" %number
10     
11 # same as above
12 for fruit in fruits:
13     print "A fruit of type:%s" % fruit
14     
15 # also we can go through mixed lists too
16 # notice we have to use %r since we don't know what's in it
17 for i in change:
18     print "I got %r" % i
19     
20 # we can also build lists, first start with an empty one
21 elements = []
22 
23 # then use the range function to do 0 to 5 counts
24 for i in range(0, 6): #range 表示一個整數的範圍,例如range(i,j)指的是範圍(i, i+1, i+2,...,j-1)
25     print "Adding %d to the list." %i
26     #append is a function that lists understand
27     elements.append(i)
28     
29 # now we can print them out too
30 for i in elements:
31     print "Element was:%d" %i
32 
33 print "the complete list elements is :", elements
ex32.py

   終端運行結果以下:

   

 

   ex32_1.py: 如何在一個非空的列表中增長特定的元素; 一次性打印列表所有元素的方式

 1 #-*-coding:utf-8-*-
 2 # 各類建立列表的方法1: 在數值列表中增長其它數字
 3 
 4 I = [1, 2, 3, 4, 5]
 5 
 6 for i in range(6,100):
 7     I.append(i)
 8     
 9 list = I #從新將列表的值賦予一個變量,而後print這個變量,即可以打印出列表了
10 print list # 一次性將列表打印出來
ex32_1.py

   終端運行結果以下:

    

 

    ex32_3.py: 列表中增長元素/列表/字符串,代碼以下:

 1 #-*-coding:utf-8-*-
 2 # 各類建立列表的方法1: 在數值列表中增長另外一個數字/字符串列表
 3 
 4 A = []
 5 I = [1, 2, 3, 4, 5]
 6 L = [6,7,8]
 7 K = [9,10,11]
 8 H = ['hello', 'my', 'friend']
 9 
10 #方法1:將兩個列表的元素放到一個列表當中,新列表的元素個數和等於兩個原始列表的元素個數總和
11 for i in L:
12     I.append(i) #這種方式,獲得的I是[1,2,3,4,5,6,7,8]
13 
14 #I.append(I) #這種方式,獲得的I是[1,2,3,4,5,[6,7,8],[6,7,8],[6,7,8]]
15     
16 list = I #從新將列表的值賦予一個變量,而後print這個變量,即可以打印出列表了,
17          # 注意:若是下面再次引用到序列I,則I的值已經變成 [1,2,3,4,5,6,7,8],再也不是原始數據了
18 print "list is:",list
19 
20 #方法2:將兩個列表的元素放到一個列表當中,新列表的元素個數和等於兩個原始列表的元素個數總和
21 X = L + K
22 list2 = X
23 print "list2 is:",list2 #獲得[6, 7, 8, 9, 10, 11]
24  
25  #將兩個列表做爲兩個元素,放到一個列表當中   
26 list3 = L
27 list4 = K
28 list5 = [list3, list4]
29 print "list5 is:", list5 # 獲得[[6, 7, 8], [9, 10, 11]]
30 
31 # 如何建立一個等長等寬,並且每列的值均相等的列表(例以下方的3*3)
32 for i in L:
33    A.append(L)  
34 list6 = A
35 print "list6 is:",list6 #這種方式,獲得的I是[[6,7,8],[6,7,8],[6,7,8]]
36 
37 # 在數值列表中增長字符串,是同樣的操做
38 for i in H:
39    L.append(i)
40 list7 = L
41 print "list7 is:", list7
ex32_3.py

   終端運行結果以下:

   

 

--------------------------------------<習題33:while循環語句>-----------------------------------

   

   while循環語句:它會一直執行它下面的代碼塊,直到while後面的布爾表達式爲False時纔會停下來。

   注意:這個循環語句 「while 2」是一個dead loop,由於這裏的2就至關於一直是True,因此這個循環語句會一直執行,除非你編碼強制讓它中止。

   while循環語句和for循環語句的區別是:while循環是用布爾表達式的結果True 或者 False來決定是否循環,通常是用在死循環中;而for循環通常是用「遍歷」來作循環的條件,例如for i in list: 意思是隻要變量i在list當中,就執行這個for循環塊,直到list裏面的全部的元素都循環一遍就結束。

   ex33.py:用while循環語句建立一個列表,通常狀況下不用while語句,由於它表複雜。代碼以下:

 1 #-*-coding:utf-8-*-
 2 # While 循環:一步一步地往列表裏增長元素
 3 
 4 i = 0
 5 numbers = []
 6 
 7 while i < 6: #此處的變量i不須要從新定義,由於在每個循環當中,都自動定義了
 8     print "At the top i is %d" %i
 9     numbers.append(i)
10     
11     i = i + 1
12     print "Numbers now:", numbers
13     print "At the bottom i is %d" %i
14     
15     
16 print "The numbers:", numbers # 輸出結果爲 The numbers: [0, 1, 2, 3, 4, 5]
ex33.py

   終端運行結果以下:

 

   ex33_1.py :用函數來達到while或for循環的目的:新建整數列表,元素的列表手動輸入。你能夠在代碼的解釋中看到循環的原理。代碼以下:

 1 #-*-coding:utf-8-*-
 2 # 自制用函數達到while或for循環的目的:整數列表
 3 
 4 I = []
 5 
 6 def creat_list():
 7     print "Now you will creat a list with functions."
 8     i = int(raw_input(">>")) #
 9     if i <= 100:
10         I.append(i)
11         print "list I is :", I
12         creat_list() # 該處是函數循環的關鍵      
13     elif i >= 100: #該處是中止函數循環的關鍵
14         print "It's the maximum list:" 
15         print I  # 返回最終版的列表
16     
17         
18 creat_list()
ex33_1.py

   終端運行結果以下:我隨便輸入的幾個數值

   

 

    ex33_2.py:這是一個頗有意思的代碼,「愛情就是毒藥」,若是你「love」,你就「die」。 它也是用手動輸入的形式,利用函數來代替while或for循環建立列表,列表的元素能夠是字符串,也能夠是數值。代碼以下:

 1 #-*-coding:utf-8-*-
 2 # 自制用函數達到while或for循環的目的:字符列表
 3 
 4 I = []
 5 
 6 print "***In this function, you can type all the words except for 'love'***"
 7 def creat_list():
 8     print "---Now you can try some words :---"
 9     a = raw_input('>>>')
10     i = a
11     
12     if 'love' in i: #該處是中止函數循環的關鍵
13         print "***oh, shit! I am poisoned by LOVE***"  
14     
15     else:  # 該處是函數循環的關鍵
16         I.append(i)
17         print I
18         print "***I am well without forbidden word!***"
19         creat_list()   
20         
21         
22 creat_list()
23 
24 
25     
ex33_2.py

   終端運行結果以下:

     

 

    ex33_3.py: 也是用手動輸入的形式,利用函數來代替while或for循環建立「二維」列表,即列表的元素爲「兩個元素的小列表」。代碼以下:

 1 #-*-coding:utf-8-*-
 2 # 自制用函數達到while或for循環的目的:二維列表
 3 
 4 I = []
 5 print "***Now you can choose two numbers and sum them, "
 6 print "\tPlease care that sum should be no more than 100***"
 7 
 8 def creat_list():
 9     print "---Please type two random numbers:---"
10     i = int(raw_input('i=')) 
11     j = int(raw_input('j='))
12     if i + j <= 100:
13         I.append([i, j])
14         print I
15         creat_list() # 該處是函數循環的關鍵      
16     else: #該處是中止函數循環的關鍵
17         print "oh, sorry! sum of i and j is bigger than 100,the list you have tried is:" 
18         print I  # 返回最終版的列表
19         
20 creat_list()
21 
22 
23     
ex33_3.py

   終端運行結果以下:

   

 

----------------------------------------<習題34:訪問列表元素>-------------------------------

   

   列表的元素的位置,牽扯到基數cardinal number和序數ordinal number的區別。例如list['a', 'b', 'c', 'd', 'e', 'f']中的元素a的序數爲1,但基數爲0,b的序數爲2,技術爲1。具體的實例見ex34.py:

 1 #-*-coding:utf-8-*-
 2 # 訪問列表的某個元素元素,序數、基數的轉換
 3 
 4 animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
 5 
 6 print animals[5], animals[4],animals[3],animals[2],animals[1],animals[0]
 7 print "\n"
 8 print animals[1]
 9 print "\n"
10 print animals * 10
11 print "\n"
12 print animals[0 ] * 10
ex34.py

 

   終端運行結果以下:

 

 第十一章預告:分支和函數、設計和調試、列表的特殊操做   

相關文章
相關標籤/搜索