<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          經(jīng)典 | 10 分鐘速成 Python3

          共 9928字,需瀏覽 20分鐘

           ·

          2020-11-08 02:00


          英文:Louie Dinh? ?翻譯:Geoff Liu???鏈接:

          https://learnxinyminutes.com/docs/zh-cn/python3-cn/


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


          注意:這篇教程是基于 Python 3 寫(xiě)的。

          # 用井字符開(kāi)頭的是單行注釋

          """ 多行字符串用三個(gè)引號(hào)
          ? ?包裹,也常被用來(lái)做多
          ? ?行注釋
          """

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

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

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

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

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

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

          # 模除
          7 % 3 # => 1

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

          # 用括號(hào)決定優(yōu)先級(jí)
          (1 + 3) * 2 ?# => 8

          # 布爾值
          True
          False

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

          # 邏輯運(yùn)算符,注意and和or都是小寫(xiě)
          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

          # 大小比較可以連起來(lái)!
          1 < 2 < 3 ?# => True
          2 < 3 < 2 ?# => False

          # 字符串用單引雙引都可以
          "這是個(gè)字符串"
          '這也是個(gè)字符串'

          # 用加號(hào)連接字符串
          "Hello " + "world!" ?# => "Hello world!"

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

          # 用.format來(lái)格式化字符串
          "{} can be {}".format("strings", "interpolated")

          # 可以重復(fù)參數(shù)以節(jié)省時(shí)間
          "{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)境運(yùn)行,也可以用老式的格式化語(yǔ)法
          "%s can be %s the %s way" % ("strings", "interpolated", "old")

          # None是一個(gè)對(duì)象
          None ?# => None

          # 當(dāng)與None進(jìn)行比較時(shí)不要用 ==,要用is。is是用來(lái)比較兩個(gè)變量是否指向同一個(gè)對(duì)象。
          "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)的變量命名是小寫(xiě),用下劃線分隔單詞
          some_var = 5
          some_var ?# => 5

          # 訪問(wèn)未賦值的變量會(huì)拋出異常
          # 參考流程控制一段來(lái)學(xué)習(xí)異常處理
          some_unknown_var ?# 拋出NameError

          # 用列表(list)儲(chǔ)存序列
          li = []
          # 創(chuàng)建列表時(shí)也可以同時(shí)賦給元素
          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
          # 取出最后一個(gè)元素
          li[-1] ?# => 3

          # 越界存取會(huì)造成IndexError
          li[4] ?# 拋出IndexError

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

          # 用del刪除任何一個(gè)元素
          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測(cè)試列表是否包含值
          1 in li ? # => True

          # 用len取列表長(zhǎng)度
          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
          # 元組周圍的括號(hào)是可以省略的
          d, e, f = 4, 5, 6
          # 交換兩個(gè)變量的值就這么簡(jiǎn)單
          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 獲得所有的鍵。
          # 因?yàn)?keys 返回一個(gè)可迭代對(duì)象,所以在這里把結(jié)果包在 list 里。我們下面會(huì)詳細(xì)介紹可迭代。
          # 注意:字典鍵的順序是不定的,你得到的結(jié)果可能和以下不同。
          list(filled_dict.keys()) ? # => ["three", "two", "one"]

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

          # 用in測(cè)試一個(gè)字典是否包含一個(gè)鍵
          "one" in filled_dict ? # => True
          1 in filled_dict ? # => False

          # 訪問(wèn)不存在的鍵會(huì)導(dǎo)致KeyError
          filled_dict["four"] ? # KeyError

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

          # setdefault方法只有當(dāng)鍵不存在的時(shí)候插入新值
          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()
          # 初始化一個(gè)集合,語(yǔ)法跟字典相似。
          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 測(cè)試集合是否包含元素
          2 in filled_set ? # => True
          10 in filled_set ? # => False

          3. 流程控制和迭代器

          # 先隨便定義一個(gè)變量
          some_var = 5

          # 這是個(gè)if語(yǔ)句。注意縮進(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)語(yǔ)句遍歷列表
          打印:
          ? ?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)"返回?cái)?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 的簡(jiǎn)寫(xiě)

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

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

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

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

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

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

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

          # 再一次調(diào)取__next__時(shí)會(huì)記得位置
          our_iterator.__next__() ?# => "two"
          our_iterator.__next__() ?# => "three"

          # 當(dāng)?shù)魉性囟既〕龊?,?huì)拋出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語(yǔ)句返回

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

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

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

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

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

          # 我們來(lái)看看結(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ù)時(shí)可以做跟上面相反的,用*展開(kāi)序列,用**展開(kāi)字典。
          args = (1, 2, 3, 4)
          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, [1, 2, 3]) ? # => [11, 12, 13]
          filter(lambda x: x > 5, [3, 4, 5, 6, 7]) ? # => [6, 7]

          # 用列表推導(dǎo)式可以簡(jiǎn)化映射和過(guò)濾。列表推導(dǎo)式的返回值是另一個(gè)列表。
          [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. 類

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

          ? ?# 類屬性,被所有此類的實(shí)例共用。
          ? ?species = "H. sapiens"

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

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

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

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

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

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

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

          # 改一個(gè)共用的類屬性
          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)入個(gè)別值
          from math import ceil, floor
          print(ceil(3.7)) ?# => 4.0
          print(floor(3.7)) ? # => 3.0

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

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

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

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

          7. 高級(jí)用法

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

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

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



          (完)
          瀏覽 49
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  十八女人毛片 | 大学生特黄特色大片免费祝频 | 无限旅游团by燕惊鸿 | 在线中文字幕亚洲 | 久久久福利视频 |