一个“MacBook”新手的Python“笨办法”自学之旅 #第十章预告:逻辑关系、布尔表达式、if/elif/else语句、循环for语句、while语句、列表及其相关

第十章预告:逻辑关系、布尔表达式、if/elif/else语句、循环for语句、while语句、列表及其相关

   这一章,最关键的是分清TrueFalse。注意这两个单词的形式必须是:首字母大写,其余小写,因为只有这样,Python才会辨别。

 ---------------------------------<习题27&28:逻辑关系和布尔表达式>------------------------------

   

   这两个习题,讲得就是我们常说的“与或非”,通过一系列的运算,得到一个True或者False。具体内容大家请参考Zed.A.Shaw著《“笨办法”学Python》的习题27和习题28。

   值得注意的是:如果在and 和 or 语句两侧,不是True或False,而是数值或字符串,Python会返回什么样的结果呢?

   下面是我在python里尝试的结果:

    

   其实上面截图里的命令行,不是布尔表达式,而是简单的and和or语句(两侧都不是True或false)不知道大家有没有总结出规律:

   1,or  语句,Python返回第一个操作对象;但是如果or语句两侧有一个False,Python返回另外一个“非False”的对象,这个语句属于布尔表达式

   2,and语句,Python返回第二个操作对象;但是如果and语句两侧有一个False,Python只返回False,这个语句属于布尔表达式

   上面的结果,于Zed.A.Shaw在习题28的第一个常见问题的解答有部分冲突,感兴趣的朋友可以自己研究一下!

--------------------------------<习题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 "	Please 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 "
"
 8 print animals[1]
 9 print "
"
10 print animals * 10
11 print "
"
12 print animals[0 ] * 10
ex34.py

   终端运行结果如下:

 第十一章预告:分支和函数、设计和调试、列表的特殊操作   

键盘敲不易,且看且仔细!
原文地址:https://www.cnblogs.com/la-route-d-ingenieur/p/11054384.html