• Learn Python The Hard Way(27--)


    Exercise 27: Memorizing Logic

    The Truth Terms
    In Python we have the following terms (characters and phrases) for determining if something is "True" or "False." Logic on a computer is all about seeing if some combination of these characters and some variables is True at that point in the program.

    - and
    - or
    - not
    - != (not equal)
    - == (equal)
    - >= (greater-than-equal)
    - <= (less-than-equal)
    - True
    - False
    

    Exercise 28: Boolean Practice

    Take each of these logic problems and write what you think the answer will be. In each case it will be either True or False. Once you have the answers written down, you will start Python in your Terminal and type each logic problem in to confirm your answers.

    True and True
    False and True
    1 == 1 and 2 == 1
    "test" == "test"
    1 == 1 or 2 != 1
    True and 1 == 1
    False and 0 != 0
    True or 1 == 1
    "test" == "testing"
    1 != 0 and 2 == 1
    "test" != "testing"
    "test" == 1
    not (True and False)
    not (1 == 1 and 0 != 1)
    not (10 == 1 or 1000 == 1000)
    not (1 != 10 or 3 == 4)
    not ("testing" == "testing" and "Zed" == "Cool Guy")
    1 == 1 and (not ("testing" == 1 or 1 == 0))
    "chunky" == "bacon" and (not (3 == 4 or 3 == 3))
    3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))
    

    Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?
    Python and many languages like to return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

    Isn't there a shortcut?
    Yes. Any and expression that has a False is immediately False, so you can stop there. Any or expression that has a True is immediately True, so you can stop there. But make sure that you can process the whole expression because later it becomes helpful.

    Exercise 29: What If

    Here is the next script of Python you will enter, which introduces you to the if-statement.

    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 and If

    Why does the code under the if need to be indented four spaces?
    A colon at the end of a line is how you tell Python you are going to create a new "block" of code, and then indenting four spaces tells Python what lines of code are in that block. This is exactly the same thing you did when you made functions in the first half of the book.
    What happens if it isn't indented?
    If it isn't indented, you will most likely create a Python error. Python expects you to indent something after you end a line with a : (colon).

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

    What happens if multiple elif blocks are True?
    Python starts and the top runs the first block that is True, so it will run only the first one.

    Exercise 31: Making Decisions

    In this script you will ask the user questions and make decisions based on their answers.

    print "You enter a dark room with three doors. Do you go through door #1, door #2 or door #3?"
    
    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. Bears runs away." % bear
    
    elif door == "2":
        print "You stare into the endless abyss at  Cthulhu's retina."
        print "1. Blueberries."
        print "2. Yello jacket clothespins."
        print "3. Understanting 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!"
    
    elif door == "3":
        print "It's your time to show solve this dangerous challenge."
        print "Choose a weapon first:"
        print "1. Gun."
        print "2. Sword."
    
        weapon = raw_input("> ")
        
        if weapon == "1":
            print "You can use this gun to kill Obama. Would you?"
            print "1. YES, OF COURSE!"
            print "2. Sorry, I'm a polite person."
            kill = raw_input("> ")
            if kill == "1":
                print "You will be the king of the seven kindoms! HAHA"
            elif kill == "2":
                print "Smart man, We all know it is difficult to kill Obama, Genleman."
            else:
                "What the hell are you doing? Why not follow the rules?"
        elif weapon == "2":
            print "oh, my old sport, actually I prefer sword, too."
            print "So ,practice it , may be I will need you do something for me in the future."
        else:
            print "What's this? I do not play with a person who does not follow the rules."
    
    else:
        print "You stumble around and fall on a knife and die.  Good job!"
    
    

    How do I tell if a number is between a range of numbers?
    You have two options: Use 0 < x < 10 or 1 <= x < 10, which is classic notation, or use x in range(1, 10).

    range(...)
        range(stop) -> list of integers
        range(start, stop[, step]) -> list of integers
        
        Return a list containing an arithmetic progression of integers.
        range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
        When step is given, it specifies the increment (or decrement).
        For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
        These are exactly the valid indices for a list of 4 elements.
    
    

    Exercise 32: Loops and Lists

    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 print them out too
    for i in elements:
        print "Element was: %d" % i
    
    1. Take a look at how you used range. Look up the range function to understand it.
      range(...)
      range(stop) -> list of integers
      range(start, stop[, step]) -> list of integers

      Return a list containing an arithmetic progression of integers.
      range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
      When step is given, it specifies the increment (or decrement).
      For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
      These are exactly the valid indices for a list of 4 elements.

    2. Could you have avoided that for-loop entirely on line 22 and just assigned range(0,6) directly to elements? YES, JUST LIKE THIS:
      elements = range(0, 6)

    3. Find the Python documentation on lists and read about them. What other operations can you do to lists besides append?

       list.append(x)
       Add an item to the end of the list; equivalent to a[len(a):] = [x].
       
       list.extend(L)
       Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
       
       list.insert(i, x)
       Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
       
       list.remove(x)
       Remove the first item from the list whose value is x. It is an error if there is no such item.
       
       list.pop([i])
       Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
       
       list.index(x)
       Return the index in the list of the first item whose value is x. It is an error if there is no such item.
       
       list.count(x)
       Return the number of times x appears in the list.
       
       list.sort(cmp=None, key=None, reverse=False)
       Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
       
       list.reverse()
       Reverse the elements of the list, in place.
      

    Exercise 33: While Loops

    Here's the problem with while-loops: Sometimes they do not stop. This is great if your intention is to just keep looping until the end of the universe. Otherwise you almost always want your loops to end eventually.

    To avoid these problems, there are some rules to follow:

     1. Make sure that you use while-loops sparingly. Usually a for-loop is better.
     2. Review your while statements and make sure that the boolean test will become False at some point.
     3. When in doubt, print out your test variable at the top and bottom of the while-loop to see what it's doing.
    
    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
    
    
    # Convert this while-loop to a function that you can call, 
    # and replace 6 in the test (i < 6) with a variable.
    # Use this function to rewrite the script to try different numbers.
    # Add another variable to the function arguments 
    # that you can pass in that lets you change the + 1 
    # so you can change how much it increments by.
    def creat_numbers(numbers, end, step):
        i = 0
        while i < end:
            print "At the top i is %d" % i
            numbers.append(i)
        
            i = i + step
            print "Numbers now: ", numbers
            print "At the bottom i is %d" % i
    
    numbers = []
    print numbers
    creat_numbers(numbers, 10, 2)
    print numbers
    
    
    # Write it to use for-loops and range. 
    # Do you need the incrementor in the middle anymore? 
    # What happens if you do not get rid of it?
    
    
    def creat_numbers(numbers, end, step):
        for i in range(0, end, step):
            print "At the top i is %d" % i
            numbers.append(i)
          #  i = i + step  # Actually it doesn't work.
           
            print "Numbers now: ", numbers
            print "At the bottom i is %d" % i
    
    numbers = []
    print numbers
    creat_numbers(numbers, 10, 1)
    print numbers
    
    

    Exercise 34: Accessing Elements of Lists

    Python starts its lists at 0 rather than 1.

    Exercise 35: Branches and Functions

    NICE ONE

    #coding=utf-8
    from sys import exit
    from os import system
    
    system("clear")
    
    def gold_room():
        print "This room is full of gold. How much do you take?"
        how_much = raw_input("Enter a num
    > ")
        try:
            how_much = int(how_much)
            if how_much < 50:                 
                print "Nice, you're not greedy, you win!"
                exit(0)
            else: 
                dead("You greedy bastard!")
        except ValueError:
            print "Please enter a num, not sting or others!"
            gold_room()
    
    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:
            choice = raw_input("> ")
    
            if choice == "take honey":
                dead("The bear looks at you then slaps your face off.")
            elif choice == "taunt bear" and not bear_moved:
                print "The bear has moved from the door. You can go through it now."
                bear_moved = True
            elif choice == "taunt bear" and bear_moved:
                dead("The bear gets pissed off and chews your leg off.")
            elif choice == "open door" and bear_moved:
                gold_room()
            elif choice == "open door" and not bear_moved:
                dead("You just go straight to the mouth of that bear.")
            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 your life or eat your head?"
    
        choice = raw_input("> ")
    
        if "flee" in choice:
            start()
        elif "head" in choice:
            dead("Well that was tasty!")
        else:
            cthulhu_room()
    
    def dead(why):
        print why, "Keep Trying!"
        print "I give you another chance.Accept it or not?"
        accept = raw_input("Y or N > ")
        if accept == "Y":
            start()
        elif accept == "N":
            exit(0)
        else:
            dead("You'd better make a right choice.")
    
    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?"
    
        choice = raw_input("> ")
    
        if choice == "left":
            bear_room()
        elif choice == "right":
            cthulhu_room()
        else:
            dead("You stumble around the room until you starve.")
    
    start()
    
    
    • sys.exit = exit(...)
      exit([status])

      Exit the interpreter by raising SystemExit(status).
      If the status is omitted or None, it defaults to zero (i.e., success).
      If the status is an integer, it will be used as the system exit status.
      If it is another kind of object, it will be printed and the system
      exit status will be one (i.e., failure).

    • 判断raw_input()的字符串是否为数字串

    #coding=utf-8
    def judge():
        a = raw_input("Enter a num:")
        try:
            a = int(a)
            print a
        except ValueError:
            print "Please enter a num, not a string or others."
    
    
    
    • What does exit(0) do?
      On many operating systems a program can abort with exit(0), and the number passed in will indicate an error or not. If you do exit(1) then it will be an error, but exit(0) will be a good exit. The reason it's backward from normal boolean logic (with 0==False is that you can use different numbers to indicate different error results. You can do exit(100) for a different error result than exit(2) or exit(1)

    Exercise 36: Designing and Debugging

    • Rules for If-Statements
    1. Every if-statement must have an else.
    2. If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
    3. Never nest if-statements more than two deep and always try to do them one deep.
    4. Treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after.
    5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.
    • WARNING
      Never be a slave to the rules in real life. For training purposes you need to follow these rules to make your mind strong, but in real life sometimes these rules are just stupid. If you think a rule is stupid, try not using it.

    • Rules for Loops

    1. Use a while-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different.
    2. Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
    • Tips for Debugging
    1. Do not use a "debugger." A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn't help and is just confusing.
    2. The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.
    3. Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.

    Exercise 37: Symbol Review(not finished)

    I have written out all the Python symbols and keywords that are important to know.

    In this lesson take each keyword and first try to write out what it does from memory. Next, search online for it and see what it really does. This may be difficult because some of these are difficult to search for, but try anyway.

    KEYWORD DESCRIPTION EXAMPLE
    and Logical and. True and False == False
    as Part of the with-as statement with X as Y: pass
  • 相关阅读:
    leetcode 198. House Robber
    leetcode 35. Search Insert Position
    一文读懂机器学习,大数据/自然语言处理/算法全有了……
    成都Uber优步司机奖励政策(1月30日)
    北京Uber优步司机奖励政策(1月30日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月30日)
    成都Uber优步司机奖励政策(1月29日)
    北京Uber优步司机奖励政策(1月29日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月29日)
    成都Uber优步司机奖励政策(1月28日)
  • 原文地址:https://www.cnblogs.com/ice-mj/p/5094824.html
Copyright © 2020-2023  润新知