一间景、作業(yè)內(nèi)容
笨辦法學(xué) Python 習(xí)題39-41以及加分題统倒。
二不跟、作業(yè)代碼:
# 習(xí)題 39: 列表的操作
ten_things = "Apples Oranges Crows Telephone Light sugar"
print("Wait there's not 10 things in that list, let's fix that.")
# ten_things.split(' ')其實(shí)是.split(ten_things, ' ')
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print("There's %d items now." % len(stuff))
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))
加分習(xí)題
1.將每一個(gè)被調(diào)用的函數(shù)以上述的方式翻譯成 Python 實(shí)際執(zhí)行的動(dòng)作甥温。例如: ' '.join(things) 其實(shí)是 join(' ', things) 刷袍。
2.將這兩種方式翻譯為自然語(yǔ)言翩隧。例如, ' '.join(things) 可以翻譯成“用 ‘ ‘ 連接(join) things”呻纹,而 join(' ', things) 的意思是“為 ‘ ‘ 和 things 調(diào)用 join 函數(shù)”堆生。這其實(shí)是同一件事情。
3.上網(wǎng)閱讀一些關(guān)于“面向?qū)ο缶幊?Object Oriented Programming)”的資料雷酪。暈了吧淑仆?嗯,我以前也是哥力。別擔(dān)心蔗怠。你將從這本書學(xué)到足夠用的關(guān)于面向?qū)ο缶幊痰幕A(chǔ)知識(shí),而以后你還可以慢慢學(xué)到更多。
4.查一下 Python中的 “class” 是什么東西寞射。不要閱讀關(guān)于其他語(yǔ)言的 “class” 的用法最住,這會(huì)讓你更糊涂。
5.dir(something) 和 something 的 class 有什么關(guān)系怠惶?
6.如果你不知道我講的是些什么東西涨缚,別擔(dān)心。程序員為了顯得自己聰明策治,于是就發(fā)明了 Opject Oriented Programming脓魏,簡(jiǎn)稱為 OOP,然后他們就開始濫用這個(gè)東西了通惫。如果你覺得這東西太難茂翔,你可以開始學(xué)一下 “函數(shù)編程(functional programming)”。
# 加分習(xí)題1.2.
ten_things = "Apples Oranges Crows Telephone Light sugar"
print("Wait there's not 10 things in that list, let's fix that.")
# ten_things.split(' ') 其實(shí)是split(ten_things, ' ')
# ten_things.split(' ') 翻譯為:用ten_things split(分割) ' '
# split(ten_things, ' ') 翻譯為:為ten_things和' '調(diào)用split(分割)函數(shù)
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
# stuff.append(next_one)其實(shí)是append(stuff, next_one)
# stuff.append(next_one) 翻譯為:用stuff append(增加)next_one
# append(stuff, next_one) 翻譯為:為stuff和next_one調(diào)用append函數(shù)
stuff.append(next_one)
print("There's %d items now." % len(stuff))
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1])
# stuff.pop()其實(shí)是pop(stuff)
# stuff.pop()翻譯為:用stuff pop(刪除)
# pop(stuff)翻譯為:為stuff調(diào)用pop函數(shù)
print(stuff.pop())
# ' '.join(stuff)其實(shí)是join(' ', stuff)
# ' '.join(stuff)翻譯為:用' 'join(連接)stuff
# join(' ', stuff)翻譯為:為' '和stuff調(diào)用join函數(shù)
print(' '.join(stuff))
# '#'.join(stuff[3:5])其實(shí)是join('#', stuff[3:5])
# '#'.join(stuff[3:5])翻譯為:用'#'join(連接)stuff[3:5]
# join('#', stuff[3:5])翻譯為:為'#'和stuff[3:5]調(diào)用join函數(shù)
print('#'.join(stuff[3:5]))
# 加分習(xí)題4.
# class(類)
class Student(object):
# 1.__init__方法的第一個(gè)參數(shù)永遠(yuǎn)是self履腋,表示創(chuàng)建的實(shí)例本身
# 2.在__init__方法內(nèi)部珊燎,就可以把各種屬性綁定到self,因?yàn)閟elf就指向創(chuàng)建的實(shí)例本身
def __init__(self, name, score):
self.name = name
self.score = score
# 有了__init__方法遵湖,在創(chuàng)建實(shí)例的時(shí)候不能傳入空的參數(shù)
# 必須傳入與__init__方法匹配的參數(shù)悔政,但self不需要傳,Python解釋器自己會(huì)把實(shí)例變量傳進(jìn)去
bart = Student('Bart Simpson', 59)
print(bart.name)
print(bart.score)
# 習(xí)題 40: 字典, 可愛的字典
# dict
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
# 條件判斷
if state in themap:
return themap[state]
else:
return "Not found."
cities['_find'] = find_city
while True:
print("State? (ENTER to quit)")
state = input("> ")
if not state: break
city_found = cities['_find'](cities, state)
print(city_found)
運(yùn)行結(jié)果如下:
"C:\Program Files\Python36\python.exe" E:/python3_project/ex40.py
State? (ENTER to quit)
> CA
San Francisco
State? (ENTER to quit)
> FL
Jacksonville
State? (ENTER to quit)
> 0
Not found.
State? (ENTER to quit)
> OR
Portland
State? (ENTER to quit)
> VT
Not found.
State? (ENTER to quit)
>
加分習(xí)題
1.在 Python 文檔中找到 dictionary (又被稱作 dicts, dict)的相關(guān)的內(nèi)容延旧,學(xué)著對(duì) dict 做更多的操作谋国。
2.找出一些 dict 無(wú)法做到的事情。例如比較重要的一個(gè)就是 dict 的內(nèi)容是無(wú)序的迁沫,你可以檢查一下看看是否真是這樣芦瘾。
3.試著把 for-loop 執(zhí)行到 dict 上面,然后試著在 for-loop 中使用 dict 的 items() 函數(shù)集畅,看看會(huì)有什么樣的結(jié)果近弟。
# 加分題1
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
# 1.把數(shù)據(jù)放入dict的方法,除了初始化時(shí)指定外挺智,還可以通過key放入
# 2.但要保證變量d已被字典所賦值的前提才不會(huì)報(bào)錯(cuò)祷愉。
>>> d['Adam'] = 67
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
通過 字典[key] 可得到value的值
>>> d['Michael']
95
>>> d['Adam'] = 67
>>> d['Adam']
67
>>> d['Jack'] = 90
>>> d['Jack']
90
由于一個(gè)key只能對(duì)應(yīng)一個(gè)value,所以多次對(duì)一個(gè)key放入value,后面的值會(huì)把前面的值沖掉:
>>> d['Jack'] = 88
>>> d['Jack']
88
如果key不存在,dict就會(huì)報(bào)錯(cuò)
>>> d['Ubuay']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Ubuay'
要避免key不存在的錯(cuò)誤逃贝,有兩種方法谣辞,一時(shí)通過'in'判斷key是否存在:
>>> 'Ubuay' in d
False
1.二是通過dict提供的get方法,如果key不存在沐扳,可以返回None
2.返回'None'的時(shí)候Python的交互式命令行不顯示結(jié)果
>>> d.get('Ubuay')
>>>
你也可以自己指定的value:意思是當(dāng)如果key不存在,可以返回你指定的value
>>> d.get('Ubuay', -1)
-1
要?jiǎng)h除一個(gè)key句占,用pop(key)方法沪摄,對(duì)應(yīng)的value也會(huì)從dict中刪除:
>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85, 'Adam': 67, 'Jack': 88}
>>> d.get('Ubuay')
>>> d.get('Ubuay', -1)
-1
1.第一行設(shè)定了key
2.第二行改變key,發(fā)現(xiàn)不可改變
>>> key = [1, 2, 3]
>>> d[key] = 'a list'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
# 習(xí)題 41: 來(lái)自 Percal 25 號(hào)行星的哥頓人
# 習(xí)題 41: 來(lái)自 Percal 25 號(hào)行星的哥頓人(Gothons)
# 通過from...import...導(dǎo)入sys模塊,將exit直接導(dǎo)入程序
# 通過from...random...導(dǎo)入random模塊杨拐,將randint直接導(dǎo)入程序
from sys import exit
from random import randint
# 定義death函數(shù)
def death():
# 將列表賦值給變量quips
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a luser.",
"I have a small puppy that's better at this."]
# len() 方法返回quips列表項(xiàng)目個(gè)數(shù)(4)祈餐。并減1
# random.randint(a, b),用于生成一個(gè)指定范圍內(nèi)的整數(shù)哄陶,
# 其中參數(shù)a是下限帆阳,參數(shù)b是上限,生成的隨機(jī)數(shù)n: a <= n <= b
# 參數(shù)為(0, 3),生成的隨機(jī)數(shù)n:0 <= n <= 3
# quips[n]用索引來(lái)訪問list中的一個(gè)元素,并打印出來(lái)
print(quips[randint(0, len(quips)-1)])
# exit(1):有錯(cuò)誤退出
exit(1)
# 定義central_corridor()函數(shù)
def central_corridor():
# 打印字符串
print("The Gothons of Planet Percal #25 have invaded your ship and destroy")
print("you entire crew. You are the last surviving member and your last")
print("mission is to get the neutron destruct bomb from the Weapons Armory,")
print("put it in the bridge, and blow the ship up after getting into an ")
print("escape pod.")
print("\n")
print("You're running down the central corridor to the Weapons Armory when")
print("a Gothon jumps put, red scaly skin, dark grimy teeth, and evil clown costume")
print("flowing around his hate filled body. He's blocking the door to the")
print("Armory and about to pull a weapon to blast you.")
# 通過input("> ")命令輸入值屋吨,并將值賦予action變量
action = input("> ")
# 通過if語(yǔ)句判斷action變量的值是否等于shoot!字符串
# 如果if語(yǔ)句判斷為True蜒谤,就把縮進(jìn)print語(yǔ)句執(zhí)行,并返回death字符串(忽略剩下的elif和else)
# 如果if語(yǔ)句判斷為False至扰,執(zhí)行elif(或else)語(yǔ)句
if action == "shoot!":
print("Quick on the draw you yank out your blaster and fire it at the Gothon.")
print("His clown costume is flowing and moving around his body, which throws")
print("off your aim. Your laser hits his costume but misses him entirely. This")
print("completely ruins his brand new costume his mother bought him, which")
print("makes him fly into an insane rage and blast you repeatedly in the face until")
print("you are dead. Then he eats you.")
return 'death'
# elif語(yǔ)句判斷action變量的值是否等于dodge!字符串
# 如果elif語(yǔ)句判斷為True鳍徽,就把縮進(jìn)print語(yǔ)句執(zhí)行,并返回death字符串(忽略剩下的elif和else)
# 如果elif語(yǔ)句判斷為False敢课,執(zhí)行下一個(gè)elif(或else)語(yǔ)句
elif action == "dodge!":
print("Like a world class boxer you dodge, weave, slip and slide right")
print("as the Gothon's blaster cranks a laser past your head.")
print("In the middle of your artful dodge your foot slips and you")
print("bang your head on the metal wall and pass out.")
print("You wake up shortly after only to die as the Gothon stomps on")
print("your head and eats you.")
return 'death'
# elif語(yǔ)句判斷action變量的值是否等于tell a joke字符串
# 如果elif語(yǔ)句判斷為True阶祭,就把縮進(jìn)print語(yǔ)句執(zhí)行,并返回laser_weapon_armory字符串(忽略剩下的elif和else)
# 如果elif語(yǔ)句判斷為False直秆,執(zhí)行剩下的else語(yǔ)句
elif action == "tell a joke":
print("Lucky for you they made you learn Gothon insults in the academy.")
print("You tell the one Gothon joke you know:")
print("Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr.")
print("The Gothon stops, tries not to laugh, then busts out laughing and can't move.")
print("While he's laughing you run up and shoot him square in the head")
print("putting him down, then jump through the Weapon Armory door.")
return 'laser_weapon_armory'
# 打印DOES NOT COMPUTE!字符串
# 返回central_corridor字符串
else:
print("DOES NOT COMPUTE!")
return 'central_corridor'
# 定義laser_weapon_armory()函數(shù)
def laser_weapon_armory():
# 打印字符串
# random.randint(a, b)濒募,用于生成一個(gè)指定范圍內(nèi)的整數(shù),
# 其中參數(shù)a是下限圾结,參數(shù)b是上限萨咳,生成的隨機(jī)數(shù)n: a <= n <= b
# 字符串包含 %d 格式化變量,變量名n均為:
# 參數(shù)為(1, 9),生成的隨機(jī)數(shù):1 <= n <= 9
# 將'%d%d%d'字符串賦值給code變量
# 通過input("[keypad]> ")命令輸入值,并將值賦予guess變量
# 將0整數(shù)賦值給guesses變量
print("You do a dive roll into the Weapon Armory, crouch and scan the room")
print("for more Gothons that might be hiding. It's dead quiet, too quiet.")
print("You stand up and run to the far side of the room and find the")
print("neutron bomb in its container. There's a keypad lock on the box")
print("and you need the code to get the bomb out. If you get the code")
print("wrong 10 times then the lock closes forever and you can't")
print("get the bomb. The code is 3 digits.")
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = input("[keypad]> ")
guesses = 0
# guess變量的值不等于code變量的值
# and運(yùn)算是與運(yùn)算疫稿,所有都為True培他,and運(yùn)算結(jié)果才是True
# while語(yǔ)句,只要條件滿足就不斷循環(huán)縮進(jìn)語(yǔ)句遗座,條件不滿足時(shí)退出循環(huán)
# 即:guess變量的值不等于code變量的布爾值為True舀凛,guesses變量的值小于10的布爾值為True時(shí),不斷循環(huán)
# 它們的and運(yùn)算結(jié)果(其中一個(gè)條件布爾值)為False時(shí)退出循環(huán)
while guess != code and guesses < 10:
# 縮進(jìn)語(yǔ)句:
# 打印"BZZZZEDDD!"字符串
# +=是加法賦值運(yùn)算符途蒋,比如c += a 等效于 c = c + a
# guesses += 1 等效于 guesses = guesses + 1猛遍,
# 即:將guesses變量的值與1整數(shù)的值相加的結(jié)果存放到guesses變量
# 通過input("[keypad]> ")命令輸入值,并將值賦予guess變量
print("BZZZZEDDD!")
guesses += 1
guess = input("[keypad]> ")
# 通過if語(yǔ)句判斷guess變量的值是否等于code變量的值:
# 如果if語(yǔ)句判斷為True号坡,就把縮進(jìn)print語(yǔ)句執(zhí)行懊烤,并返回'the_bridge'字符串(忽略剩下的elif和else)
# 如果if語(yǔ)句判斷為False,執(zhí)行elif或else語(yǔ)句
if guess == code:
print("The container clicks open and the seal breaks, letting gas out.")
print("You grab the neutron bomb and run as fast you can to the")
print("bridge_where you must place it in the right spot.")
return 'the_bridge'
# 打印字符串
# 返回 'death'字符串
else:
print("The lock buzzes one last time and then you hear sickening")
print("melting sound as the mechanism is fused together.")
print("You decide to sit there, and finally the Gothons blow up the")
print("ship from their ship and you die.")
return 'death'
# 定義the_bridge()函數(shù)
def the_bridge():
# 打印字符串
print("You burst onto the Bridge with the neutron destruct bomb")
print("under your arm and surprise 5 Gothons who are trying to")
print("take control of the ship. Each of them has an even uglier")
print("clown costume than the last. They haven't pulled their")
print("weapons out yet, as they see the active bomb under your")
print("arm and don't want to set it off.")
# 通過input("> ")命令輸入值宽堆,并將值賦予 action 變量
action = input("> ")
# 通過if語(yǔ)句判斷 action 變量的值是否等于"throw the bomb"字符串的值:
# 如果if語(yǔ)句判斷為True腌紧,就把縮進(jìn)print語(yǔ)句執(zhí)行,并返回'death'字符串(忽略剩下的elif和else)
# 如果if語(yǔ)句判斷為False畜隶,執(zhí)行elif或else語(yǔ)句
if action == "throw the bomb":
print("In a panic you throw the bomb at the group of Gothons")
print("and make a leap for the door. Right as you drop it a")
print("Gothon shoots you right in the back killing you.")
print("As you die you see another Gothon frantically try to disarm")
print("the bomb. You die knowing they will probably blow up when")
print("it goes off.")
return 'death'
# elif語(yǔ)句判斷 action 變量的值是否等于"slowly place the bomb"字符串
# 如果elif語(yǔ)句判斷為True壁肋,就把縮進(jìn)print語(yǔ)句執(zhí)行号胚,并返回'escape_pod'字符串(忽略剩下的elif和else)
# 如果elif語(yǔ)句判斷為False,執(zhí)行下一個(gè)elif(或else)語(yǔ)句
elif action == "slowly place the bomb":
print("You point your blaster at the bomb under you arm")
print("and the Gothons put their hands up and start to sweat.")
print("You inch backward to the door, open it, and then carefully")
print("place the bomb on the floor, pointing your blaster at it.")
print("You then jump back through the door, punch the close button")
print("and blast the lock so the Gothons can't get out.")
print("Now that the bomb is placed you run to the escape pod to")
print("get off this tin can.")
return 'escape_pod'
# 打印字符串
# 返回"the_bright"字符串
else:
print("DOES NOT COMPUTE!")
return "the_bright"
# 定義 escape_pod()函數(shù)
def escape_pod():
# 打印字符串
# 將randint(1,5)隨機(jī)數(shù)賦值給good_pod變量
# 通過input("[pod #]> ")命令輸入值浸遗,并將值賦予 guess 變量
print("You rush through the ship desperately trying to make it to")
print("the escape pod before the whole ship explodes. It seems like")
print("hardly any Gothons are on the ship, so your run is clear of")
print("interference. You get to the chamber with the escape pods, and")
print("now need to pick one to take. Some of them could be damaged")
print("but you don't have time to look. There's 5 pods, which one")
print("do you take?")
good_pod = randint(1,5)
guess = input("[pod #]> ")
# 在上一段代碼中input()返回的數(shù)據(jù)類型是str猫胁,str不能直接與整數(shù)比較,
# 必須先把str轉(zhuǎn)換成整數(shù)(注:int無(wú)法轉(zhuǎn)換「不是合法數(shù)字」的字符串):
# 通過if語(yǔ)句判斷 int(guess) 變量的值是否不等于 good_pod 變量的值:
# 如果if語(yǔ)句判斷為True跛锌,就把縮進(jìn)print語(yǔ)句執(zhí)行弃秆,并返回'death'字符串(忽略剩下的elif和else)
# 如果if語(yǔ)句判斷為False,執(zhí)行elif或else語(yǔ)句
if int(guess) != good_pod:
print("You jump into pod %s and hit the eject button." % guess)
print("The pod escapes out into the world of space, then")
print("implodes as the hull ruptures, crushing your body")
print("into jam jelly.")
return 'death'
# 打印字符串
# exit(0):無(wú)錯(cuò)誤退出
else:
print("You jump into pod %s and hit the eject button." % guess)
print("The pod easily slides out into space heading to")
print("the planet below. Asit flies to the planet, you look")
print("back and see you ship implode then explode like a")
print("bright star, taking out the Gothon ship at the same")
print("time. You won!")
exit(0)
# 使用dict創(chuàng)建ROOMS字典髓帽,使用鍵-值(key-value)存儲(chǔ)
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
# 定義函數(shù)runner()參數(shù)分別為map菠赚,start
def runner(map, start):
# 將start變量賦值給next變量
next = start
# while語(yǔ)句,只要條件滿足就不斷循環(huán)縮進(jìn)語(yǔ)句氢卡,條件不滿足時(shí)退出循環(huán)
while True:
room = map[next]
print("\n--------")
next = room()
runner(ROOMS, 'central_corridor')