"Learn Python the Hard Way"学习笔记6——Exercise36-40

Exercise 36 设计和调试

最好的调试程序的方法是使用print,在各个你想要检查的关键环节将关键变量打印出来,从而检查哪里是否有错。debugger的结果会迷惑你。

作业:设计一个类似exercise35的小游戏并实现
最后的一点建议:所有的程序员面对一个新的大项目都会手足无措感到害怕。他们会拖延,避免面对这种畏惧,最后项目不能完成甚至根本没有开始。我是这样。所有人都是。避免这种事情发生的最好办法就是列出来所有你需要做的事,接下来各个击破。

(最近看了Stranger Things2,所以设计了一个小游戏测试你是怪奇物语里的哪个角色哈哈哈)

from sys import exit

def start():
    print "You will take a test to find which role you will be in \'Stranger Things\'!"
    print "You're in Hawkins town."
    print "And today is Halloween,where will you be tonight?"
    print "1.Get candy!"
    print "2.Stay home and watch horror movies."
    print "3.Go to party!"
    
    option1 = raw_input("> ")
    if option1 == "1":
        print "Congraulations! You are a lovely child."
        game()
    elif option1 == "2":
        dead("Congraulations! You are a tired adult.")
    elif option1 == "3":
        dead("Congraulations! You are a dumb teenager.")
    else:
        dead("Maybe you don't belong to this town.Where do you come from?")


def dead(result):
    print "Well you have done the test.And you are ..."
    print result
    exit(0)

    
def game():
    print "You come to get candy with your friends."
    print "And there is a game room."
    print "Will you go in there?"
    print "1.yes"
    print "2.no"
    
    option2 = raw_input("> ")
    if option2 == "1":
        gab()    
    elif option2 == "2":
        dead("Hello, Eleven. :) ")
    else:
        dead("Maybe you don't belong to this town.Where do you come from?")    

        
def gab():
    print "Are you a boy or a girl?"
    print "1.boy"
    print "2.girl"
    
    option3 = raw_input("> ")
    if option3 == "1":
        school()
    elif option3 == "2":
        dead("Of course you are Mad Max!!")
    else:
        dead("Maybe you don't belong to this town.Where do you come from?")
        

def school():
    print "Today is weekday."
    print "Your science teacher is teaching something interesting."
    print "What are you doing now?"
    print "1.I am listening to the class."
    print "2.Oh no,I am late for school!"
    print "3.Well I am staying at my bed."  
    
    option4 = raw_input("> ")
    if option4 == "1":
        last()
    elif option4 == "2":
        dead("Dustin! Stay away from your pet!!")
    elif option4 == "3":
        dead("You must be poor Will.")
    else:
        dead("Maybe you don't belong to this town.Where do you come from?")



def last():
    print "Your friend Will seems not well these days."
    print "What do you think of his disease?"
    print "1.It must have some relationship with Eleven and the upside world."
    print "2.Well it's nothing serious."
    options5 = raw_input("> ")
    if options5 == "1":
        dead("Mike. Everyone loves you.")
    elif options5 == "2":
        dead("LUCAS!")
    else:
        dead("Maybe you don't belong to this town.Where do you come from?")
        
        
start()

一个测试结果:

output36.png

Exercise 37 复习符号

一些不熟悉的符号
Keywords:

del 从字典中删除    del X[Y]
global 定义一个全局变量    global X
with 一个变量的别名    with X as Y: pass
assert 声明    assert False, "Error!"
pass 该代码块为空    def empty(): pass
yield 暂停,返回给调用者    def X(): yield Y; X().next()
exec 将字符串作为python代码执行    exec 'print "hello"'
raise 代码出错时,抛出一个异常    raise ValueError("No")
finally 不管是否有异常,finally代码块都执行    finally: pass
is 类似==,判断相等    1 is 1 == True
lambda 创建一个无名函数    s = lambda y: y ** y; s(3)

String Escape Sequences:

\a Bell
\b 退格
\f Formfeed
\n 换行
\r Carriage
\v 垂直的tab

String Format:

%d 格式化整数 (不包含浮点数).  "%d" % 45 == '45'
%i 与%d相同    "%i" % 45 == '45'
%o 8进制数字    "%o" % 1000 == '1750'
%u 负数   "%u" % -1000 == '-1000'
%x 小写的十六进制数字    "%x" % 1000 == '3e8'
%X 大写的十六进制数字    "%X" % 1000 == '3E8'
%e 小写 'e'的指数标记  "%e" % 1000 == '1.000000e+03'
%E 大写 'e'的指数标记  "%E" % 1000 == '1.000000E+03'
%f 浮点数  "%f" % 10.34 == '10.340000'
%F 与%f相同    "%F" % 10.34 == '10.340000'
%g %f 或者 %e中较短的一个   "%g" % 10.34 == '10.34'
%G %F 或者 %E中较短的一个   "%G" % 10.34 == '10.34'
%c 字符格式化    "%c" % 34 == '"'
%% 表示百分号%   "%g%%" % 10.34 == '10.34%'

Operators:

// 整除,得到除法的商    2 // 4.0 == 0.0
<> 不等于  4 <> 5 == True
() 括号   len('hi') == 2
[] 列表括号 [1,3,4]
{} 字典括号 {'x': 5, 'y': 10}
@ 装饰符   @classmethod
*= 乘等于  x = 1; x *= 2
/= 除等于  x = 1; x /= 2
//= 整除等于    x = 1; x //= 2
%= 模除等于 x = 1; x %= 2
**= 幂乘等于    x = 1; x **= 2

Exercise 38 列表操作

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print "Wait there's not 10 things in that list, let's fix that."

stuff = ten_things.split(' ')
more_stuff = ["Days","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] #whoa! fancy
print stuff.pop()
#join stuff with ' ' between them
print ' '.join(stuff)
#join the fourth and fifth things in stuff with '#' between them
print '#'.join(stuff[3:5])

Exercise 39 可爱的字典

#create a mapping of state to abbreviation
states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}

#create a basic set of states and some cities in them
cities = {
    'CA': 'San Francisco',
    'MI': 'Detroit',
    'FL': 'Jacksonville'
}

#add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

#print out some cities
print '-' * 10
print "NY State has: ",cities['NY']
print "OR State has: ",cities['OR']

#print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']

#do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]

#print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
    print "%s is abbreviated %s" % (state, abbrev)
    
#print every city in state
print '-' * 10
for abbrev, city in cities.items():
    print "%s has the city %s" % (abbrev, city)
    
#now do both at the same time
print '-' * 10
for state, abbrev in states.items():
    print "%s state is abbreviated %s and has city %s" % (
        state, abbrev, cities[abbrev])
        
print '-' * 10
#safely get an abbreviation by state that might not be there
state = states.get('Texas', None)

if not state:
    print "Sorry, no Texas."
    
#get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city

Q:字典和列表的区别?

list是一个有序的项目列表,dict是匹配一些项目(称为“key”)和其他项目(称为“value”)

Exercise 40 模块,对象和类

考虑一下之前是怎样运用模块的:

#this goes in mystuff.py
def apple():
    print "I AM APPLES!"
#this is just a variable
tangerine = "Living reflection of a dream"

之后,可以import这个模块,然后使用其中的apple函数和变量。

import mystuff

mystuff.apple()
print mystuff.tangerine

类就像是模块。类的作用是组织一系列的函数和数据并将它们放在一个容器里,这样你可以通过.操作符访问到它们。创建类:

class MyStuff(object):
    def __init__(self):
        self.tangerine = "And now a thousand years between"
        
    def apple(self):
        print "I AM CLASSY APPLES!"

Q:为什么使用类而不是模块?
你可以使用Mystuff这个类,还可以创建更多的类,而他们之间也不会互相冲突。当你导入一个模块时,你的整个项目也就只有一个这个模块。

我们对模块最常见的操作是import。相对应的,对类的相似操作被称作instantiate(实例化)。当一个类被实例化,你就得到一个类的对象。实例化刚才的那个类:

thing = MyStuff()
thing.apple()
print thing.tangerine

举个例子:

class Song(object):
    
    def __init__(self, lyrics):
        self.lyrics = lyrics
        
    def sing_me_a_song(self):
        for line in self.lyrics:
            print line
            
happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])
                   
bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])
                        
happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容