分支就是分叉,由一个点来发散,发散成两条线以上,编程语句用if-elif-if和逻辑表达式,这个逻辑表达式就是前面所说的布尔运算,得出的结果就是“真”或“假”,以此为依据来决定是否执行冒号后面的代码块,好的,终于描述清楚了,摘选这几课中比较有用的代码贴上来
ex30
# coding=utf-8
people = 30
cars = 40
trucks = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if trucks > cars:
print "That's too many trucks."
elif trucks < cars:
print "Maybe we could take the trucks."
else:
print "We still can't decide."
if people > trucks:
print "Alright, let's just take the trucks."
else:
print "Fine, let's stay home then."
ex31
# coding=utf-8
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door =raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1.Take the cake."
print "2.Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
elif door =="2":
print "You stare into the endless abyes at Cthulhu's retina."
print "1.Blueberries."
print "2.Yellow jacket clothespins."
print "3.Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or "2":
print "Your body survives powered by a mind of jello. Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
else:
print "You stumble around and fall on a knife and die. Good job!"
ex32
# coding = utf-8
the_count = [1,2,3,4,5]
fruits =['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
for number in the_count:
print "This is count %d" % number
for fruit in fruits:
print "A fruit of type: %s" % fruit
for i in change:
print "I got %r" % i
elements = []
for i in range(0,6):
print "Adding %d to the list." % i
elements.append(i)
for i in elements:
print "Element was : %d" % i
在后续的程序中,for与列表有大量的配合使用
说一下range()函数,这个函数也是会在后面大量的使用,整理一下它的几个点:
- range(1,5)输出的结果是[1, 2, 3, 4]记住是没有5的
- range(5) 输出的结果是[0,1, 2, 3, 4]记住是从0开始的
- range(0,5,2)输出的结果是[0,2,4],输出的顺序是0,加2,加2,最大值要小于5
列表的相关的操作,现有列表list = [1, 2, 3, 4, 5]
- list[0:]列出0号(包括0)以后的内容,结果是[1,2,3,4,5]
- list[1:]列出1号(包括1)以后的内容,结果是[2,3,4,5]
- list[:-1]列出-1号之前的(这里不包括-1号)结果是[1,2,3,4]
- list[2:-2]结果是[3]
- list[::]与list[:]效果一样都是显示全部
- list[::2]结果是[1,3,5]
- list[2::]结果是[3,4,5]
- list[::-1]结果是[5,4,3,2,1]
- list[::-2]结果是[5,3,1]
append()函数就是给list在最后面添加数据,例如:
list.append('haha'),那么上面的列表内容就是[1, 2, 3, 4, 5,‘haha'],网上搜了一下,还有个相似的函数,扩展一下extend():
list.extend(['haha','lulu'])结果是list = [1, 2, 3, 4, 5,'haha','lulu']