author:headsen chen
date: 2018-06-01 15:51:05
习题 31: 作出决定(if + raw_input)
[root@localhost py]# cat desition.py #!/usr/bin/env python 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 abyss 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 insanity == "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!"
[root@localhost py]# python desition.py You enter a dark room with two doors. Do you go through door #1 or door #2? > 1 There's a giant bear here eating a cheese cake. What do you do? 1. Take the cake. 2. Scream at the bear. > 2 The bear eats your legs off. Good job!
习题 32: 循环和列表
[root@localhost py]# cat list-for.py #!/usr/bin/env python the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Element was: %d" % i
[root@localhost py]# python list-for.py This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarters' Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5
习题 33: While 循环
[root@localhost py]# cat while.py #!/usr/bin/env python i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num
[root@localhost py]# python while.py At the top i is 0 Numbers now: [0] At the bottom i is 1 At the top i is 1 Numbers now: [0, 1] At the bottom i is 2 At the top i is 2 Numbers now: [0, 1, 2] At the bottom i is 3 At the top i is 3 Numbers now: [0, 1, 2, 3] At the bottom i is 4 At the top i is 4 Numbers now: [0, 1, 2, 3, 4] At the bottom i is 5 At the top i is 5 Numbers now: [0, 1, 2, 3, 4, 5] At the bottom i is 6 The numbers: 0 1 2 3 4 5
习题 35: 分支和函数
[root@localhost py]# cat func-if.py #!/usr/bin/env python from sys import exit def gold_room(): print "This room is full of gold. How much do you take?" next = raw_input("> ") if "0" in next or "1" in next: how_much = int(next) else: dead("Man, learn to type a number.") if how_much < 50: print "Nice, you're not greedy, you win!" exit(0) else: dead("You greedy bastard!") def bear_room(): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" bear_moved = False while True: next = raw_input("> ") if next == "take honey": dead("The bear looks at you then slaps your face off.") elif next == "taunt bear" and not bear_moved: print "The bear has moved from the door. You can go through it now." bear_moved = True elif next == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif next == "open door" and bear_moved: gold_room() else: print "I got no idea what that means." def cthulhu_room(): print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane." print "Do you flee for your life or eat your head?" next = raw_input("> ") if "flee" in next: start() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print why, "Good job!" exit(0) def start(): print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input("> ") if next == "left": bear_room() elif next == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start()
[root@localhost py]# python func-if.py You are in a dark room. There is a door to your right and left. Which one do you take? > left There is a bear here. The bear has a bunch of honey. The fat bear is in front of another door. How are you going to move the bear? > taunt bear The bear has moved from the door. You can go through it now. > open door This room is full of gold. How much do you take? > asf Man, learn to type a number. Good job!
习题 36: 复习各种符号
关键字 and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 数据类型 True False None strings numbers floats lists 字符串转义序列(Escape Sequences) \\ \' \" \a \b \f \n \r \t \v 字符串格式化(String Formats) %d -------》 数字 %i %o %u %x %X %e %E %f --------》 小数 %F %g %G %c %r ----------》%r 调用 rper函数打印字符串,repr函数返回的字符串是加上了转义序列,是直接书写的字符串的形式 %s ----------》%s 调用 str函数打印字符串,str函数返回原始字符串 %% 操作符号 + - * ** / // % < > <= >= == != <> ( ) [ ] { } @ , : . = ; += -= *= /= //= %= **=
习题37:列表
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 = ["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] # whoa! fancy print stuff.pop() print ' '.join(stuff) # what? cool! print '#'.join(stuff[3:5]) # super stellar! [root@localhost py]# python ex ex15_sample.txt ex39.py [root@localhost py]# python ex39.py Wait there's not 10 things in that list, let's fix that. Adding: Boy There's 7 items now. Adding: Girl There's 8 items now. Adding: Banana There's 9 items now. Adding: Corn There's 10 items now. There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] Let's do some things with stuff. Oranges Corn Corn Apples Oranges Crows Telephone Light Sugar Boy Girl Banana Telephone#Light
习题 40: 字典
[root@localhost py]# cat dict.py #!/usr/bin/env python cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' print cities def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." # ok pay attention! cities['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break # this line is the most important ever! study! city_found = cities['_find'](cities, state) print city_found
习题 41: 来自 Percal 25 号行星的哥顿人
[root@localhost py]# cat gothons.py #!/usr/bin/env python from sys import exit from random import randint def death(): 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."] print quips[randint(0, len(quips)-1)] exit(1) def central_corridor(): print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" print "your 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 out, 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." action = raw_input("> ") 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 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 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' else: print "DOES NOT COMPUTE!" return 'central_corridor' def laser_weapon_armory(): 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 = raw_input("[keypad]> ") guesses = 0 while guess != code and guesses < 10: print "BZZZZEDDD!" guesses += 1 guess = raw_input("[keypad]> ") 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 as you can to the" print "bridge where you must place it in the right spot." return 'the_bridge' else: print "The lock buzzes one last time and then you hear a 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' 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." action = raw_input("> ") 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 action == "slowly place the bomb": print "You point your blaster at the bomb under your 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' else: print "DOES NOT COMPUTE!" return "the_bridge" def escape_pod(): 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 = raw_input("[pod #]> ") if int(guess) != good_pod: print "You jump into pod %s and hit the eject button." % guess print "The pod escapes out into the void of space,then" print "implodes as the hull ruptures, crushing your body" print "into jam jelly." return 'death' 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. As it flies to the planet,you look" print "back and see your ship implode then explode like a" print "bright star, taking out the Gothon ship at the same" print "time. You won!" exit(0) ROOMS = { 'death': death, 'central_corridor': central_corridor, 'laser_weapon_armory': laser_weapon_armory, 'the_bridge': the_bridge, 'escape_pod': escape_pod } def runner(map, start): next = start while True: room = map[next] print "\n--------" next = room() runner(ROOMS, 'central_corridor')
习题 42: 类(高级的函数)
[root@localhost py]# cat class.py #!/usr/bin/env python class TheThing(object): def __init__(self): self.number = 0 def some_function(self): print "I got called." def add_me_up(self, more): self.number += more return self.number # two different things a = TheThing() b = TheThing() a.some_function() b.some_function() print a.add_me_up(20) print a.add_me_up(20) print b.add_me_up(30) print b.add_me_up(30) print a.number print b.number
[root@localhost py]# python class.py I got called. I got called. 20 40 30 60 40 60
总结:
参数里的 self 了吧?你知道它是什么东西吗?对了,它就是 Python 创建的额外的一个参数,有了它你才能实现 a.some_function()
__init__ 函数是为Python class 设置内部变量的方式。你可以使用.将它们设置到self上面。你的__init__不应该做太多的事情,这会让 class 变得难以使用。
class 使用 “camel case(驼峰式大小写)”,例如 SuperGoldFactory
普通函数应该使用 “underscore format(下划线隔词)”, my_awesome_hair ,
永远永远都使用 class Name(object) 的方式定义 class