美文网首页
"Learn Python the Hard Way"学习笔记5

"Learn Python the Hard Way"学习笔记5

作者: los_pollos | 来源:发表于2017-10-26 21:30 被阅读0次

    Exercise 24 更多练习

    print "Let's practice everything."
    print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
    
    poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from institution
    and requires an explanation
    \n\t\twhere there is none.
    """
    
    print "-----------------"
    print poem
    print "-----------------"
    
    
    five = 10 - 2 + 3 - 6
    print "This should be five: %s" % five
    
    def secret_formula(started):
        jelly_beans = started * 500
        jars = jelly_beans / 1000
        crates = jars / 100
        return jelly_beans, jars, crates 
      
      
    start_point = 10000
    beans, jars, crates = secret_formula(start_point)
    
    print "With a starting point of: %d" % start_point
    print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
    
    start_point = start_point / 10
    
    print "We can also do it this way:"
    print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
    

    执行结果:


    output24.png

    Exercise 25 更多更多练习

    def break_words(stuff):
        """This function will break up words for us."""
        words = stuff.split(' ')
        return words
        
    def sort_words(words):
        """Sorts the words."""
        return sorted(words)
        
    def print_first_word(words):
        """Prints the first word after poping it off."""
        word = words.pop(0)
        print word
        
    def print_last_word(words):
        """Prints the last word after poping it off."""
        word = words.pop(-1)
        print word
        
    def sort_sentence(sentence):
        """Takes in a full sentence and returns the sorted words."""
        words = break_words(sentence)
        return sort_words(words)
        
    def print_first_and_last(sentence):
        """Prints the first and the last words of the sentence."""
        words = break_words(sentence)
        print_first_word(words)
        print_last_word(words)
        
    def print_first_and_last_sorted(sentence):
        """Sorts the words then prints the first and last one."""
        words = sort_sentence(sentence)
        print_first_word(words)
        print_last_word(words)    
    

    在PowerShell里执行:

    output25.png

    执行help(ex25)和help(ex25.break_words)。这是你得到模块帮助文档的方式。 所谓帮助文档就是你定义函数时放在"""之间的东西,它们也被称作documentation comments (文档注解)。
    重复键入ex25. 是很烦的一件事情。有一个捷径就是用from ex25 import *的方式导入模组。这相当于说:“我要把 ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,开一个新的会话,看看你所有的函数是不是已经在那里了。

    Exercise 26 恭喜,开始测试吧

    检查https://learnpythonthehardway.org/book/exercise26.txt的代码错误即可

    Exercise 27 逻辑

    and or not != == >= <= True False
    

    Exercise 28 布尔值练习

    Exercise 29 if

    people = 20
    cats = 30
    dogs = 15
    
    if people < cats:
        print "Too many cats! The world is doomed!"
        
    if people > cats:
        print "Not many cats! The world is saved!"
        
    if people < dogs:
        print "The world is drooled on!"
        
    if people > dogs:
        print "The world is dry!"
        
    dogs += 5
    
    if people >= dogs:
        print "People are greater than or equal to dogs."
        
    if people <= dogs:
        print "People are less than or equal to dogs."
        
    if people == dogs:
        print "People are dogs."
    

    Exercise 30 else和if

    people = 30
    cars = 40
    buses = 15
    
    
    if cars > people:
        print "We should like the cars."
    elif cars < people:
        print "We should not take the cars."
    else:
        print "We can't decide."
        
    if buses > cars:
        print "That's too many buses."
    elif buses < cars:
        print "Maybe we could take the buses."
    else:
        print "We still can't decide."
        
    if people > buses:
        print "Alright, let's just take the buses."
    else:
        print "Fine, let's stay home then."
    

    Exercise 31 做决定

    print "You enter a dark home 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!"
    

    Exercise 32 循环和列表

    the_count = [1, 2, 3, 4, 5]
    fruits = ['apples', 'oranges', 'pears', 'apricots']
    change = [1, 'pennies', 2, 'dims', 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 lists." % 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   
    

    Exercise 33 while循环

    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 
    

    Exercise 34 获取列表元素

    Exercise 35 分支和函数

    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 st 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 yo 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()
    

    执行结果:


    output35.png

    相关文章

      网友评论

          本文标题:"Learn Python the Hard Way"学习笔记5

          本文链接:https://www.haomeiwen.com/subject/mwbhpxtx.html