15分でPythonの基本的な文法と一部の特性を理解させます.

24868 ワード

本稿では、Pythonの基本的な構文と一部の特性を迅速に理解するために、オブジェクトに向けて、プログラミングの経験があるパートナーを対象としています.
前言
    # Python       ‘#’
    """ Python     
          """,      
          ,      。
    """

1.基本タイプと演算子
    #         3
    3  # => 3

    #     
    1 + 1  # => 2
    8 - 1  # => 7
    10 * 2  # => 20
    35 / 5  # => 7

    #             ,           
    # ( python2.x  。   ,Python3.x            ,      )
    5 / 2  # => 2
    10/-3 #python3    -3.3333333333333335 python2    -4
    10/3 #python3    3.3333333333333335 python2    3 
    #            , Python2 ,      ,         



    #               , Python            
    2.0     #      
    11.0 / 4.0  #         2.75 !      ? 

    #   ‘//’     ,python3           .
    5 // 3     # => 1
    5.0 // 3.0 # => 1.0 
    -5 // 3  # => -2
    -5.0 // 3.0 # => -2.0


    from __future__ import division #        __future__     
                                    #  python2   python3   
    11/4    # => 2.75  ...     
    11//4   # => 2 ...     

    #      
    7 % 3 # => 1

    #     2 4  
    2**4 # => 16

    #    ,   ,    
    (1 + 3) * 2  # => 8

    #      
    #  :or   and             
    True and False #=>   False
    False or True #=>   True

    #          ,  0 ,     
    0 and 2 #=> 0
    -5 or 0 #=> -5
    0 == False #=> True
    2 == True #=> False
    1 == True #=> True

    #  not   
    not True  # => False
    not False  # => True

    #     “==”,      True ,     False
    1 == 1  # => True
    2 == 1  # => False

    #     “!=”,          True,    Flase
    1 != 1  # => False
    2 != 1  # => True

    #   /           
    1 < 10  # => True
    1 > 10  # => False
    2 <= 2  # => True
    2 >= 2  # => True

    # Python             ,
           #        False,    False
    1 < 2 < 3  # => True
    2 < 3 < 2  # => False

    #      "    '      
    "This is a string."
    'This is also a string.'

    #          +      ,       ?
    "Hello " + "world!"  # => "Hello world!"
    #      '+' ,           
    "Hello " "world!"  # => "Hello world!"

     #     *  ,        ,   ;
             importantNote = "        
" * 3 print (importantNote) """ : """ "Hello" * 3 # => "HelloHelloHello" # "This is a string"[0] # => 'T' # % , #( C/C++ %d ,%s , # python , ) x = 'apple' y = 'lemon' z = "The items in the basket are %s and %s" % (x,y) # .format() , "{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None ,None None, None # => None # None , “==” , “is” "etc" is None # => False None is None # => True #“is" , # # “is”, , “is” # bool # # - None # - 0 (e.g., 0, 0L, 0.0, 0j) # - 、 (e.g., '', (), []) # - 、 (e.g., {}, set()) # - : # https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ # # All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False

2.変数と集合
    #    print()
    print ("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!

     #          
    input_string_var = raw_input("Enter some data: ") #        
     input_var = input("Enter some data: ") # python                  “”or''
    #   :  python 3 , input()   raw_input()   

    #  Python          ,python          
    some_var = 5    
    some_var  # => 5


    # if           ,         “  ‘yahool’  3  2  ,    2“
    "yahoo!" if 3 > 2 else 2  # => "yahoo!"

リスト#リスト#
    # python      
    li = []
    #                
    other_li = [4, 5, 6]

    # append           
    li.append(1)    # li is now [1]
    li.append(2)    # li is now [1, 2]
    li.append(4)    # li is now [1, 2, 4]
    li.append(3)    # li is now [1, 2, 4, 3]
    # pop         
    li.pop()        # => 3 and li is now [1, 2, 4]
    #      append  
    li.append(3)    # li is now [1, 2, 4, 3] again.

    #   []                
           #(  ,index       )
    li[0]  # => 1
    #      []            
    li[0] = 42
    li[0]  # => 42
    #   []       ,             
    li[-1]  # => 3

    #              ,    。
    #     insert()     ,                 
    li[4]  # Raises an IndexError

    #     [:],           
    # (It's a closed/open range for you mathy types.)
    #        ,  li[1:3],      index 1、2    ,
    #             []     
    li[1:3]  # => [2, 4]
    #        ,          。
    li[2:]  # => [4, 3]
    li[:3]  # => [1, 2, 4]

    # [::2]     [0]  ,   2   
    li[::2]   # =>[1, 4]
    # [::-1]      ,-          , 1    ,  1            
    li[::-1]   # => [3, 4, 2, 1]
    # []         [  :  :  ]
    # li[start:end:step]

    #  "del"              
    del li[2]   # li is now [1, 2, 3]

    #     “+”          , :     +   ,   (set) +   -
    li + other_li   # => [1, 2, 3, 4, 5, 6]


    #     "extend()"         
    li.extend(other_li)   # Now li is [1, 2, 3, 4, 5, 6]

    # Remove     del   , remove      ,   index
    li.remove(2)  # li is now [1, 3, 4, 5, 6]
    li.remove(2)  #   remove        ,    

    #          ,      ,  index     ,        
    li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again

    #       index
    li.index(2)  # => 1
    li.index(7)  #   

    # "in"                 
    1 in li   # => True

    # "len()"           
    len(li)   # => 6

メタグループ
    # Tuples(  )            ,          
    tup = (1, 2, 3)
    tup[0]   # => 1
    tup[0] = 3  #        

    #              (     )
    len(tup)   # => 3
    tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)
    tup[:2]   # => (1, 2)
    2 in tup   # => True

    #            
    a, b, c = (1, 2, 3)     # a  1,b 2,c 3
    d, e, f = 4, 5, 6       #            
    #                
    g = 4, 5, 6             # => (4, 5, 6)
    # Python          :            
    e, d = d, e     # d is now 5 and e is now 4

辞書
    # Python      
    empty_dict = {}
    #              
    filled_dict = {"one": 1, "two": 2, "three": 3}

    #     [] key         
    filled_dict["one"]   # => 1

    #     "keys()"          key 
    filled_dict.keys()   # => ["three", "two", "one"]
    # Note -    keys           .
    #                 

    #    "values()"             ,
     #                   
    filled_dict.values()   # => [3, 2, 1]


    #      "in"                 ,       
    "one" in filled_dict   # => True
    1 in filled_dict   # => False

    #       key  ,Python   
    filled_dict["four"]   # KeyError

    #  "get()"              
    filled_dict.get("one")   # => 1
    filled_dict.get("four")   # => None
    #          ,get           ,
    #              
    filled_dict.get("one", 4)   # => 1
    filled_dict.get("four", 4)   # => 4


    #               ,  []      
    filled_dict["four"] = 4  # now, filled_dict["four"] => 4

    # "setdefault()"          
    #     :              ,setdefault()     
    filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
    filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

しゅうごう
    empty_set = set()
    #    set        set()   
    some_set = set([1, 2, 2, 3, 4])   # some_set is now set([1, 2, 3, 4])

    #          !         !         !
    another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])

    # Python2.7  ,{}         
    filled_set = {1, 2, 2, 3, 4}   # => {1, 2, 3, 4}

    # Add           
    filled_set.add(5)   # filled_set is now {1, 2, 3, 4, 5}

    #      &      
    other_set = {3, 4, 5, 6}
    filled_set & other_set   # => {3, 4, 5}

    #   |      
    filled_set | other_set   # => {1, 2, 3, 4, 5, 6}

    #    -       
    {1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}

    #    ^       
    {1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

    #    >=                 
    {1, 2} >= {1, 2, 3} # => False

    #    <=                
    {1, 2} <= {1, 2, 3} # => True

    #    in             
    2 in filled_set   # => True
    10 in filled_set   # => False

Pythonデータセットタイプまとめ
  • リスト定義li=[1,2,3,4,[Hello World](リストに任意の基本タイプを含めることができる)
  • タプル定義tup=(1,2,3,4)(リストと似ていますが、タプルは変更できません)
  • 辞書定義方式dic={"one":2,"tow":3,"three":0}(辞書、辞書ですか.key:value方式で存在)
  • 集合定義方式set=set(1,2,3,4)or set={1,2,3,4}(集合内の要素は一意であり、集合サポート&|^+-操作)
  • 3.Python論理演算子
        #       
        some_var = 5
    
        #   if      
        if some_var > 10:
            print "some_var is totally bigger than 10."
        elif some_var < 10:    # This elif clause is optional.
            print "some_var is smaller than 10."
        else:           # This is optional too.
            print "some_var is indeed 10."
    
    
        """
              for...in...      :
            dog is a mammal
            cat is a mammal
            mouse is a mammal
        """
        for animal in ["dog", "cat", "mouse"]:
            # You can use {0} to interpolate formatted strings. (See above.)
            print "{0} is a mammal".format(animal)
    
        """
          "range()"   ,  for     
        prints:
            0
            1
            2
            3
        """
        for i in range(4):
            print i
    
        """
        "range(lower, upper)"    lower   upper  ,
           :range          
        prints:
            4
            5
            6
            7
        """
        for i in range(4, 8):
            print i
    
        """
        while   
        prints:
            0
            1
            2
            3
        """
        x = 0
        while x < 4:
            print x
            x += 1  # Shorthand for x = x + 1
    
        # Python   try/except   
    
        # Python2.6     ,  try...except...:
        try:
            # raise       。     raise  ,raise          。
            raise IndexError("This is an index error")
        except IndexError as e:
            pass    # pass    ,    
        except (TypeError, NameError):
            pass    # python           
        else:   # Python         ,           
            print "All good!"   
        finally: #  finally           
            print "We can clean up resources here"
    
        #  with  ,    try....except...    [with  ](http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/)
        with open("myfile.txt") as f:
            for line in f:
                print line

    4.関数
        # def        
        def add(x, y):
            print "x is {0} and y is {1}".format(x, y)
            return x + y    #    return  
    
        #       
        add(5, 6)   # => prints out "x is 5 and y is 6" and returns 11
    
        # Python      ,             
        add(y=6, x=5)   # Keyword arguments can arrive in any order.
    
    
        # Python        
        #         *        
        def varargs(*args):
            return args
    
        varargs(1, 2, 3)   # => (1, 2, 3)
    
        #     **     Key              
    
        def keyword_args(**kwargs):
            return kwargs
    
        #       **     ,Python           
        keyword_args(big="foot", loch="ness")   # => {"big": "foot", "loch": "ness"}
    
    
        #             ,      :
        def all_the_args(*args, **kwargs):
            print args
            print kwargs
        """
        all_the_args(1, 2, a=3, b=4) prints:
            (1, 2)
            {"a": 3, "b": 4}
        """
    
        #       ,      :
        args = (1, 2, 3, 4)
        kwargs = {"a": 3, "b": 4}
        all_the_args(*args)   # equivalent to foo(1, 2, 3, 4)
        all_the_args(**kwargs)   # equivalent to foo(a=3, b=4)
        all_the_args(*args, **kwargs)   # equivalent to foo(1, 2, 3, 4, a=3, b=4)
    
        #              *    **   ,        
        def pass_all_the_args(*args, **kwargs):
            all_the_args(*args, **kwargs)
            print varargs(*args)
            print keyword_args(**kwargs)
    
        #      X
        x = 5
    
        def set_x(num):
            #            ,     gloabl   ,         
            x = num # => 43
            print x # => 43
    
        def set_global_x(num):
            global x
            print x # => 5
            x = num #   global    ,            
            print x # => 6
    
        set_x(43)
        set_global_x(6)
    
        #             /*    ,    */
        def create_adder(x):
            def adder(y):
                return x + y
            return adder
    
        add_10 = create_adder(10)
        add_10(3)   # => 13
    
        # Lambda           
        (lambda x: x > 2)(3)   # => True 
        (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
    
        # map              
        map(add_10, [1, 2, 3])   # => [11, 12, 13]
        map(max, [1, 2, 3], [4, 2, 1])   # => [4, 2, 3]
    
        filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]
    
        #              ,       :
        #add_10(i)     for...in...      ,         。
        [add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]
        [x for x in [3, 4, 5, 6, 7] if x > 5]   # => [6, 7]

    5.Pythonのクラス
        #           Human ,   object 
        # Python         , class Human(object,orangOutang)
        class Human(object):
    
            #    
            species = "H. sapiens"   
                        __species = "Other.sapiens" #    ,         
    
            # __init__(),     ,python         ,        ,
            #             ,               ,    :   
            #__init__      ,        
            # __del__       ,       
            #__repr__   ,  
            #__setitem__      
            #__getitem__       
            #__len__    
            #__cmp__    
            #__call__    
            #__add__   
            #__sub__   
            #__mul__   
            #__div__   
            #__mod__    
            #__pow__  
    
            def __init__(self, name):
                #       ,    ,         
                #         
                self.name = name
                self.age = 0
    
            #            self       
            #(               )
            def say(self, msg):
                return "{0}: {1}".format(self.name, msg)
    
            #    
            @classmethod
            def get_species(cls):
                return cls.species
    
            #     ,
            @staticmethod
            def grunt():
                return "*grunt*"
    
            # A property is just like a getter.
            # It turns the method age() into an read-only attribute
            # of the same name.
            #property  ,   getter
            @property
            def age(self):
                return self._age
    
            # This allows the property to be set
            @age.setter
            def age(self, age):
                self._age = age
    
            # This allows the property to be deleted
            @age.deleter
            def age(self):
                del self._age
    
    
        #    
        i = Human(name="Ian")
        print i.say("hi")     # prints out "Ian: hi"
    
        j = Human("Joel")
        print j.say("hello")  # prints out "Joel: hello"
    
        #       "."
        i.get_species()   # => "H. sapiens"
    
        #      
        Human.species = "H. neanderthalensis"
        i.get_species()   # => "H. neanderthalensis"
        j.get_species()   # => "H. neanderthalensis"
    
        #       
        Human.grunt()   # => "*grunt*"
    
        #  age  
        i.age = 42
    
        #   age 
        i.age # => 42
    
        #   age
        del i.age
        i.age  # => raises an AttributeError

    6.Pythonのモジュール(ライブラリ)
        # Python    *.py        
        import math
        print math.sqrt(16)  # => 4
    
        #             /  
        from math import ceil, floor
        print ceil(3.7)  # => 4.0
        print floor(3.7)   # => 3.0
    
        #      *      
        # Warning: this is not recommended
        from math import *
    
        #math       m
        math.sqrt(16) == m.sqrt(16)   # => True
        #       sqrt 
        from math import sqrt
        math.sqrt == m.sqrt == sqrt  # => True
    
    
    
        #python       
        import math
        dir(math)
    
        # If you have a Python script named math.py in the same
        # folder as your current script, the file math.py will 
        # be loaded instead of the built-in Python module. 
        # This happens because the local folder has priority
        # over Python's built-in libraries. 
    
        #            Python       math.py
        #      math.py       Python  
        #   Python                    

    7.Pythonにおける高度な特性(ジェネレータ、装飾器:wraps)
        # Generators ,      Python               。
        #     ,  yield               。
        #        ,           ,           。           
        #     return  ,        yield    。
        for i in iterable:
            yield i + i
    
        xrange_ = xrange(1, 900000000)
    
        for i in double_numbers(xrange_):
            print i
            if i >= 30:
                break
    
    
    
        #    wraps,wraps    
        # Beg will call say. If say_please is True then it will change the returned
        # message
        from functools import wraps
    
        def beg(target_function):
            @wraps(target_function)
            def wrapper(*args, **kwargs):
                msg, say_please = target_function(*args, **kwargs)
                if say_please:
                    return "{} {}".format(msg, "Please! I am poor :(")
                return msg
    
            return wrapper
    
        @beg
    def say(say_please=False):
        msg = "Can you buy me a beer?"
        return msg, say_please
    
    print say()  # Can you buy me a beer?
    print say(say_please=True)  # Can you buy me a beer? Please! I am poor :

    [1]learnxinyminutes、このコードの大部分はこのサイトから取って、ここでこのサイトの作者に感謝します!
    作者:Mr_C
    リンク:http://www.jianshu.com/p/36ae91c38279
    出典:簡書
    著作権は作者の所有である.商業転載は著者に連絡して許可を得てください.非商業転載は出典を明記してください.