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()
一个测试结果:
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()