乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      10 分鐘速成 Python3

       taotao_2016 2019-01-23

      鏈接:https:///docs/zh-cn/python3-cn/

      Python 是由吉多·范羅蘇姆(Guido Van Rossum)在 90 年代早期設(shè)計。 它是如今最常用的編程語言之一。它的語法簡潔且優(yōu)美,幾乎就是可執(zhí)行的偽代碼。

      注意:這篇教程是基于 Python 3 寫的。源代碼下載:https:///docs/files/learnpython3-cn.py

      #用井字符開頭的是單行注釋

      ''' 多行字符串用三個引號
          包裹,也常被用來做多
          行注釋
      '''

      1. 原始數(shù)據(jù)類型和運算符

      # 整數(shù)
      3  # => 3

      # 算術(shù)沒有什么出乎意料的
      1 + 1  # => 2
      8 - 1  # => 7
      10 * 2  # => 20

      # 但是除法例外,會自動轉(zhuǎn)換成浮點數(shù)
      35 / 5  # => 7.0
      5 / 3  # => 1.6666666666666667

      # 整數(shù)除法的結(jié)果都是向下取整
      5 // 3     # => 1
      5.0 // 3.0 # => 1.0 # 浮點數(shù)也可以
      -5 // 3  # => -2
      -5.0 // 3.0 # => -2.0

      # 浮點數(shù)的運算結(jié)果也是浮點數(shù)
      3 * 2.0 # => 6.0

      # 模除
      7 % 3 # => 1

      # x的y次方
      2**4 # => 16

      # 用括號決定優(yōu)先級
      (1 + 3) * 2  # => 8

      # 布爾值
      True
      False

      # 用not取非
      not True  # => False
      not False  # => True

      # 邏輯運算符,注意and和or都是小寫
      True and False # => False
      False or True # => True

      # 整數(shù)也可以當(dāng)作布爾值
      0 and 2 # => 0
      -5 or 0 # => -5
      0 == False # => True
      2 == True # => False
      1 == True # => True

      # 用==判斷相等
      1 == 1  # => True
      2 == 1  # => False

      # 用!=判斷不等
      1 != 1  # => False
      2 != 1  # => True

      # 比較大小
      1 < 10  # => True
      1 > 10  # => False
      2 <= 2  # => True
      2 >= 2  # => True

      # 大小比較可以連起來!
      1 < 2 < 3  # => True
      2 < 3 < 2  # => False

      # 字符串用單引雙引都可以
      '這是個字符串'
      '這也是個字符串'

      # 用加號連接字符串
      'Hello ' + 'world!'  # => 'Hello world!'

      # 字符串可以被當(dāng)作字符列表
      'This is a string'[0]  # => 'T'

      # 用.format來格式化字符串
      '{} can be {}'.format('strings''interpolated')

      # 可以重復(fù)參數(shù)以節(jié)省時間
      '{0} be nimble, {0} be quick, {0} jump over the {1}'.format('Jack''candle stick')
      # => 'Jack be nimble, Jack be quick, Jack jump over the candle stick'

      # 如果不想數(shù)參數(shù),可以用關(guān)鍵字
      '{name} wants to eat {food}'.format(name='Bob', food='lasagna'
      # => 'Bob wants to eat lasagna'

      # 如果你的Python3程序也要在Python2.5以下環(huán)境運行,也可以用老式的格式化語法
      '%s can be %s the %s way' % ('strings''interpolated''old')

      # None是一個對象
      None  # => None

      # 當(dāng)與None進(jìn)行比較時不要用 ==,要用is。is是用來比較兩個變量是否指向同一個對象。
      'etc' is None  # => False
      None is None  # => True

      # None,0,空字符串,空列表,空字典都算是False
      # 所有其他值都是True
      bool(0)  # => False
      bool('')  # => False
      bool([]) # => False
      bool({}) # => False

      2. 變量和集合

      # print是內(nèi)置的打印函數(shù)
      print('I'm Python. Nice to meet you!')

      # 在給變量賦值前不用提前聲明
      # 傳統(tǒng)的變量命名是小寫,用下劃線分隔單詞
      some_var = 5
      some_var  # => 5

      # 訪問未賦值的變量會拋出異常
      # 參考流程控制一段來學(xué)習(xí)異常處理
      some_unknown_var  # 拋出NameError

      # 用列表(list)儲存序列
      li = []
      # 創(chuàng)建列表時也可以同時賦給元素
      other_li = [4, 5, 6]

      # 用append在列表最后追加元素
      li.append(1)    # li現(xiàn)在是[1]
      li.append(2)    # li現(xiàn)在是[1, 2]
      li.append(4)    # li現(xiàn)在是[1, 2, 4]
      li.append(3)    # li現(xiàn)在是[1, 2, 4, 3]
      # 用pop從列表尾部刪除
      li.pop()        # => 3 且li現(xiàn)在是[1, 2, 4]
      # 把3再放回去
      li.append(3)    # li變回[1, 2, 4, 3]

      # 列表存取跟數(shù)組一樣
      li[0]  # => 1
      # 取出最后一個元素
      li[-1]  # => 3

      # 越界存取會造成IndexError
      li[4]  # 拋出IndexError

      # 列表有切割語法
      li[1:3]  # => [2, 4]
      # 取尾
      li[2:]  # => [4, 3]
      # 取頭
      li[:3]  # => [1, 2, 4]
      # 隔一個取一個
      li[::2]   # =>[1, 4]
      # 倒排列表
      li[::-1]   # => [3, 4, 2, 1]
      # 可以用三個參數(shù)的任何組合來構(gòu)建切割
      # li[始:終:步伐]

      # 用del刪除任何一個元素
      del li[2]   # li is now [1, 2, 3]

      # 列表可以相加
      # 注意:li和other_li的值都不變
      li + other_li   # => [1, 2, 3, 4, 5, 6]

      # 用extend拼接列表
      li.extend(other_li)   # li現(xiàn)在是[1, 2, 3, 4, 5, 6]

      # 用in測試列表是否包含值
      1 in li   # => True

      # 用len取列表長度
      len(li)   # => 6


      # 元組是不可改變的序列
      tup = (1, 2, 3)
      tup[0]   # => 1
      tup[0] = 3  # 拋出TypeError

      # 列表允許的操作元組大都可以
      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)     # 現(xiàn)在a是1,b是2,c是3
      # 元組周圍的括號是可以省略的
      d, e, f = 4, 5, 6
      # 交換兩個變量的值就這么簡單
      e, d = d, e     # 現(xiàn)在d是5,e是4


      # 用字典表達(dá)映射關(guān)系
      empty_dict = {}
      # 初始化的字典
      filled_dict = {'one': 1, 'two': 2, 'three': 3}

      # 用[]取值
      filled_dict['one']   # => 1


      # 用 keys 獲得所有的鍵。
      # 因為 keys 返回一個可迭代對象,所以在這里把結(jié)果包在 list 里。我們下面會詳細(xì)介紹可迭代。
      # 注意:字典鍵的順序是不定的,你得到的結(jié)果可能和以下不同。
      list(filled_dict.keys())   # => ['three', 'two', 'one']


      # 用values獲得所有的值。跟keys一樣,要用list包起來,順序也可能不同。
      list(filled_dict.values())   # => [3, 2, 1]


      # 用in測試一個字典是否包含一個鍵
      'one' in filled_dict   # => True
      1 in filled_dict   # => False

      # 訪問不存在的鍵會導(dǎo)致KeyError
      filled_dict['four']   # KeyError

      # 用get來避免KeyError
      filled_dict.get('one')   # => 1
      filled_dict.get('four')   # => None
      # 當(dāng)鍵不存在的時候get方法可以返回默認(rèn)值
      filled_dict.get('one', 4)   # => 1
      filled_dict.get('four', 4)   # => 4

      # setdefault方法只有當(dāng)鍵不存在的時候插入新值
      filled_dict.setdefault('five', 5)  # filled_dict['five']設(shè)為5
      filled_dict.setdefault('five', 6)  # filled_dict['five']還是5

      # 字典賦值
      filled_dict.update({'four':4}) # => {'one': 1, 'two': 2, 'three': 3, 'four': 4}
      filled_dict['four'] = 4  # 另一種賦值方法

      # 用del刪除
      del filled_dict['one']  # 從filled_dict中把one刪除


      # 用set表達(dá)集合
      empty_set = set()
      # 初始化一個集合,語法跟字典相似。
      some_set = {1, 1, 2, 2, 3, 4}   # some_set現(xiàn)在是{1, 2, 3, 4}

      # 可以把集合賦值于變量
      filled_set = some_set

      # 為集合添加元素
      filled_set.add(5)   # filled_set現(xiàn)在是{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}

      # - 取補(bǔ)集
      {1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}

      # in 測試集合是否包含元素
      2 in filled_set   # => True
      10 in filled_set   # => False

      3. 流程控制和迭代器

      # 先隨便定義一個變量
      some_var = 5

      # 這是個if語句。注意縮進(jìn)在Python里是有意義的
      # 印出'some_var比10小'
      if some_var > 10:
          print('some_var比10大')
      elif some_var < 10:    # elif句是可選的
          print('some_var比10小')
      else:                  # else也是可選的
          print('some_var就是10')


      '''
      用for循環(huán)語句遍歷列表
      打印:
          dog is a mammal
          cat is a mammal
          mouse is a mammal
      '''

      for animal in ['dog''cat''mouse']:
          print('{} is a mammal'.format(animal))

      '''
      'range(number)'返回數(shù)字列表從0到給的數(shù)字
      打印:
          0
          1
          2
          3
      '''

      for i in range(4):
          print(i)

      '''
      while循環(huán)直到條件不滿足
      打印:
          0
          1
          2
          3
      '''

      x = 0
      while x < 4:
          print(x)
          x += 1  # x = x + 1 的簡寫

      # 用try/except塊處理異常狀況
      try:
          # 用raise拋出異常
          raise IndexError('This is an index error')
      except IndexError as e:
          pass    # pass是無操作,但是應(yīng)該在這里處理錯誤
      except (TypeError, NameError):
          pass    # 可以同時處理不同類的錯誤
      else:   # else語句是可選的,必須在所有的except之后
          print('All good!')   # 只有當(dāng)try運行完沒有錯誤的時候這句才會運行


      # Python提供一個叫做可迭代(iterable)的基本抽象。一個可迭代對象是可以被當(dāng)作序列
      # 的對象。比如說上面range返回的對象就是可迭代的。

      filled_dict = {'one'1'two'2'three'3}
      our_iterable = filled_dict.keys()
      print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一個實現(xiàn)可迭代接口的對象

      # 可迭代對象可以遍歷
      for i in our_iterable:
          print(i)    # 打印 one, two, three

      # 但是不可以隨機(jī)訪問
      our_iterable[1]  # 拋出TypeError

      # 可迭代對象知道怎么生成迭代器
      our_iterator = iter(our_iterable)

      # 迭代器是一個可以記住遍歷的位置的對象
      # 用__next__可以取得下一個元素
      our_iterator.__next__()  # => 'one'

      # 再一次調(diào)取__next__時會記得位置
      our_iterator.__next__()  # => 'two'
      our_iterator.__next__()  # => 'three'

      # 當(dāng)?shù)魉性囟既〕龊?,會拋出StopIteration
      our_iterator.__next__() # 拋出StopIteration

      # 可以用list一次取出迭代器所有的元素
      list(filled_dict.keys())  # => Returns ['one', 'two', 'three']

      4. 函數(shù)

      # 用def定義新函數(shù)
      def add(x, y):
          print('x is {} and y is {}'.format(x, y))
          return x + y    # 用return語句返回

      # 調(diào)用函數(shù)
      add(56)   # => 印出'x is 5 and y is 6'并且返回11

      # 也可以用關(guān)鍵字參數(shù)來調(diào)用函數(shù)
      add(y=6, x=5)   # 關(guān)鍵字參數(shù)可以用任何順序


      # 我們可以定義一個可變參數(shù)函數(shù)
      def varargs(*args):
          return args

      varargs(123)   # => (1, 2, 3)


      # 我們也可以定義一個關(guān)鍵字可變參數(shù)函數(shù)
      def keyword_args(**kwargs):
          return kwargs

      # 我們來看看結(jié)果是什么:
      keyword_args(big='foot', loch='ness')   # => {'big': 'foot', 'loch': 'ness'}


      # 這兩種可變參數(shù)可以混著用
      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}
      '''


      # 調(diào)用可變參數(shù)函數(shù)時可以做跟上面相反的,用*展開序列,用**展開字典。
      args = (1234)
      kwargs = {'a'3'b'4}
      all_the_args(*args)   # 相當(dāng)于 foo(1, 2, 3, 4)
      all_the_args(**kwargs)   # 相當(dāng)于 foo(a=3, b=4)
      all_the_args(*args, **kwargs)   # 相當(dāng)于 foo(1, 2, 3, 4, a=3, b=4)


      # 函數(shù)作用域
      x = 5

      def setX(num):
          # 局部作用域的x和全局域的x是不同的
          x = num # => 43
          print (x) # => 43

      def setGlobalX(num):
          global x
          print (x) # => 5
          x = num # 現(xiàn)在全局域的x被賦值
          print (x) # => 6

      setX(43)
      setGlobalX(6)


      # 函數(shù)在Python是一等公民
      def create_adder(x):
          def adder(y):
              return x + y
          return adder

      add_10 = create_adder(10)
      add_10(3)   # => 13

      # 也有匿名函數(shù)
      (lambda x: x > 2)(3)   # => True

      # 內(nèi)置的高階函數(shù)
      map(add_10, [123])   # => [11, 12, 13]
      filter(lambda x: x > 5, [34567])   # => [6, 7]

      # 用列表推導(dǎo)式可以簡化映射和過濾。列表推導(dǎo)式的返回值是另一個列表。
      [add_10(i) for i in [123]]  # => [11, 12, 13]
      [x for x in [34567if x > 5]   # => [6, 7]

      5. 類

      # 定義一個繼承object的類
      class Human(object):

          # 類屬性,被所有此類的實例共用。
          species = 'H. sapiens'

          # 構(gòu)造方法,當(dāng)實例被初始化時被調(diào)用。注意名字前后的雙下劃線,這是表明這個屬
          # 性或方法對Python有特殊意義,但是允許用戶自行定義。你自己取名時不應(yīng)該用這
          # 種格式。
          def __init__(self, name):
              # Assign the argument to the instance's name attribute
              self.name = name

          # 實例方法,第一個參數(shù)總是self,就是這個實例對象
          def say(self, msg):
              return '{name}: {message}'.format(name=self.name, message=msg)

          # 類方法,被所有此類的實例共用。第一個參數(shù)是這個類對象。
          @classmethod
          def get_species(cls):
              return cls.species

          # 靜態(tài)方法。調(diào)用時沒有實例或類的綁定。
          @staticmethod
          def grunt():
              return '*grunt*'


      # 構(gòu)造一個實例
      i = Human(name='Ian')
      print(i.say('hi'))     # 印出 'Ian: hi'

      j = Human('Joel')
      print(j.say('hello'))  # 印出 'Joel: hello'

      # 調(diào)用一個類方法
      i.get_species()   # => 'H. sapiens'

      # 改一個共用的類屬性
      Human.species = 'H. neanderthalensis'
      i.get_species()   # => 'H. neanderthalensis'
      j.get_species()   # => 'H. neanderthalensis'

      # 調(diào)用靜態(tài)方法
      Human.grunt()   # => '*grunt*'

      6. 模塊

      # 用import導(dǎo)入模塊
      import math
      print(math.sqrt(16))  # => 4.0

      # 也可以從模塊中導(dǎo)入個別值
      from math import ceil, floor
      print(ceil(3.7))  # => 4.0
      print(floor(3.7))   # => 3.0

      # 可以導(dǎo)入一個模塊中所有值
      # 警告:不建議這么做
      from math import *

      # 如此縮寫模塊名字
      import math as m
      math.sqrt(16) == m.sqrt(16)   # => True

      # Python模塊其實就是普通的Python文件。你可以自己寫,然后導(dǎo)入,
      # 模塊的名字就是文件的名字。

      # 你可以這樣列出一個模塊里所有的值
      import math
      dir(math)

      7. 高級用法

      # 用生成器(generators)方便地寫惰性運算
      def double_numbers(iterable):
          for i in iterable:
              yield i + i

      # 生成器只有在需要時才計算下一個值。它們每一次循環(huán)只生成一個值,而不是把所有的
      # 值全部算好。
      #
      # range的返回值也是一個生成器,不然一個1到900000000的列表會花很多時間和內(nèi)存。
      #
      # 如果你想用一個Python的關(guān)鍵字當(dāng)作變量名,可以加一個下劃線來區(qū)分。
      range_ = range(1900000000)
      # 當(dāng)找到一個 >=30 的結(jié)果就會停
      # 這意味著 `double_numbers` 不會生成大于30的數(shù)。
      for i in double_numbers(range_):
          print(i)
          if i >= 30:
              break


      # 裝飾器(decorators)
      # 這個例子中,beg裝飾say
      # beg會先調(diào)用say。如果返回的say_please為真,beg會改變返回的字符串。
      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 :(

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多