分支就是分叉女器,由一個(gè)點(diǎn)來(lái)發(fā)散酸役,發(fā)散成兩條線以上,編程語(yǔ)句用if-elif-if和邏輯表達(dá)式驾胆,這個(gè)邏輯表達(dá)式就是前面所說(shuō)的布爾運(yùn)算涣澡,得出的結(jié)果就是“真”或“假”,以此為依據(jù)來(lái)決定是否執(zhí)行冒號(hào)后面的代碼塊丧诺,好的入桂,終于描述清楚了,摘選這幾課中比較有用的代碼貼上來(lái)
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
在后續(xù)的程序中驳阎,for與列表有大量的配合使用
說(shuō)一下range()函數(shù)抗愁,這個(gè)函數(shù)也是會(huì)在后面大量的使用馁蒂,整理一下它的幾個(gè)點(diǎn):
- range(1,5)輸出的結(jié)果是[1, 2, 3, 4]記住是沒(méi)有5的
- range(5) 輸出的結(jié)果是[0,1, 2, 3, 4]記住是從0開(kāi)始的
- range(0,5,2)輸出的結(jié)果是[0,2,4],輸出的順序是0,加2蜘腌,加2沫屡,最大值要小于5
列表的相關(guān)的操作,現(xiàn)有列表list = [1, 2, 3, 4, 5]
- list[0:]列出0號(hào)(包括0)以后的內(nèi)容撮珠,結(jié)果是[1,2,3,4,5]
- list[1:]列出1號(hào)(包括1)以后的內(nèi)容沮脖,結(jié)果是[2,3,4,5]
- list[:-1]列出-1號(hào)之前的(這里不包括-1號(hào))結(jié)果是[1,2,3,4]
- list[2:-2]結(jié)果是[3]
- list[::]與list[:]效果一樣都是顯示全部
- list[::2]結(jié)果是[1,3,5]
- list[2::]結(jié)果是[3,4,5]
- list[::-1]結(jié)果是[5,4,3,2,1]
- list[::-2]結(jié)果是[5,3,1]
append()函數(shù)就是給list在最后面添加數(shù)據(jù),例如:
list.append('haha'),那么上面的列表內(nèi)容就是[1, 2, 3, 4, 5芯急,‘haha'],網(wǎng)上搜了一下勺届,還有個(gè)相似的函數(shù),擴(kuò)展一下extend():
list.extend(['haha','lulu'])結(jié)果是list = [1, 2, 3, 4, 5,'haha','lulu']