日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python语法学习

發(fā)布時(shí)間:2025/5/22 python 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python语法学习 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# 單行注釋 """ 多行字符串可以用 三個(gè)引號(hào)包裹,不過這也可以被當(dāng)做 多行注釋 """#################################################### ## 1. 原始數(shù)據(jù)類型和操作符 ##################################################### 數(shù)字類型 3 # => 3# 簡(jiǎn)單的算數(shù) 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7# 整數(shù)的除法會(huì)自動(dòng)取整 5 / 2 # => 2# 要做精確的除法,我們需要引入浮點(diǎn)數(shù) 2.0 # 浮點(diǎn)數(shù) 11.0 / 4.0 # => 2.75 精確多了# 括號(hào)具有最高優(yōu)先級(jí) (1 + 3) * 2 # => 8# 布爾值也是基本的數(shù)據(jù)類型 True False# 用 not 來取非 not True # => False not False # => 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# 比較運(yùn)算可以連起來寫! 1 < 2 < 3 # => True 2 < 3 < 2 # => False# 字符串通過 " 或 ' 括起來 "This is a string." 'This is also a string.'# 字符串通過加號(hào)拼接 "Hello " + "world!" # => "Hello world!"# 字符串可以被視為字符的列表 "This is a string"[0] # => 'T'# % 可以用來格式化字符串 "%s can be %s" % ("strings", "interpolated")# 也可以用 format 方法來格式化字符串 # 推薦使用這個(gè)方法 "{0} can be {1}".format("strings", "formatted") # 也可以用變量名代替數(shù)字 "{name} wants to eat {food}".format(name="Bob", food="lasagna")# None 是對(duì)象 None # => None# 不要用相等 `==` 符號(hào)來和None進(jìn)行比較 # 要用 `is` "etc" is None # => False None is None # => True# 'is' 可以用來比較對(duì)象的相等性 # 這個(gè)操作符在比較原始數(shù)據(jù)時(shí)沒多少用,但是比較對(duì)象時(shí)必不可少# None, 0, 和空字符串都被算作 False # 其他的均為 True 0 == False # => True "" == False # => True#################################################### ## 2. 變量和集合 ##################################################### 很方便的輸出 print "I'm Python. Nice to meet you!"# 給變量賦值前不需要事先聲明 some_var = 5 # 一般建議使用小寫字母和下劃線組合來做為變量名 some_var # => 5# 訪問未賦值的變量會(huì)拋出異常 # 可以查看控制流程一節(jié)來了解如何異常處理 some_other_var # 拋出 NameError# if 語句可以作為表達(dá)式來使用 "yahoo!" if 3 > 2 else 2 # => "yahoo!"# 列表用來保存序列 li = [] # 可以直接初始化列表 other_li = [4, 5, 6]# 在列表末尾添加元素 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] # 移除列表末尾元素 li.pop() # => 3 li 現(xiàn)在是 [1, 2, 4] # 重新加進(jìn)去 li.append(3) # li is now [1, 2, 4, 3] again.# 像其他語言訪問數(shù)組一樣訪問列表 li[0] # => 1 # 訪問最后一個(gè)元素 li[-1] # => 3# 越界會(huì)拋出異常 li[4] # 拋出越界異常# 切片語法需要用到列表的索引訪問 # 可以看做數(shù)學(xué)之中左閉右開區(qū)間 li[1:3] # => [2, 4] # 省略開頭的元素 li[2:] # => [4, 3] # 省略末尾的元素 li[:3] # => [1, 2, 4]# 刪除特定元素 del li[2] # li 現(xiàn)在是 [1, 2, 3]# 合并列表 li + other_li # => [1, 2, 3, 4, 5, 6] - 并不會(huì)不改變這兩個(gè)列表# 通過拼接來合并列表 li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6]# 用 in 來返回元素是否在列表中 1 in li # => True# 返回列表長(zhǎng)度 len(li) # => 6# 元組類似于列表,但它是不可改變的 tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # 類型錯(cuò)誤# 對(duì)于大多數(shù)的列表操作,也適用于元組 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True# 你可以將元組解包賦給多個(gè)變量 a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 # 如果不加括號(hào),將會(huì)被自動(dòng)視為元組 d, e, f = 4, 5, 6 # 現(xiàn)在我們可以看看交換兩個(gè)數(shù)字是多么容易的事 e, d = d, e # d 是 5,e 是 4# 字典用來儲(chǔ)存映射關(guān)系 empty_dict = {} # 字典初始化 filled_dict = {"one": 1, "two": 2, "three": 3}# 字典也用中括號(hào)訪問元素 filled_dict["one"] # => 1# 把所有的鍵保存在列表中 filled_dict.keys() # => ["three", "two", "one"] # 鍵的順序并不是唯一的,得到的不一定是這個(gè)順序# 把所有的值保存在列表中 filled_dict.values() # => [3, 2, 1] # 和鍵的順序相同# 判斷一個(gè)鍵是否存在 "one" in filled_dict # => True 1 in filled_dict # => False# 查詢一個(gè)不存在的鍵會(huì)拋出 KeyError filled_dict["four"] # KeyError# 用 get 方法來避免 KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None # get 方法支持在不存在的時(shí)候返回一個(gè)默認(rèn)值 filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4# setdefault 是一個(gè)更安全的添加字典元素的方法 filled_dict.setdefault("five", 5) # filled_dict["five"] 的值為 5 filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5# 集合儲(chǔ)存無順序的元素 empty_set = set() # 初始化一個(gè)集合 some_set = set([1, 2, 2, 3, 4]) # some_set 現(xiàn)在是 set([1, 2, 3, 4])# Python 2.7 之后,大括號(hào)可以用來表示集合 filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}# 向集合添加元素 filled_set.add(5) # filled_set 現(xiàn)在是 {1, 2, 3, 4, 5}# 用 & 來計(jì)算集合的交 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5}# 用 | 來計(jì)算集合的并 filled_set | other_set # => {1, 2, 3, 4, 5, 6}# 用 - 來計(jì)算集合的差 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4}# 用 in 來判斷元素是否存在于集合中 2 in filled_set # => True 10 in filled_set # => False#################################################### ## 3. 控制流程 ##################################################### 新建一個(gè)變量 some_var = 5# 這是個(gè) if 語句,在 python 中縮進(jìn)是很重要的。 # 下面的代碼片段將會(huì)輸出 "some var is smaller than 10" if some_var > 10:print "some_var is totally bigger than 10." elif some_var < 10: # 這個(gè) elif 語句是不必須的print "some_var is smaller than 10." else: # 這個(gè) else 也不是必須的print "some_var is indeed 10."""" 用for循環(huán)遍歷列表 輸出: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]:# 你可以用 % 來格式化字符串print "%s is a mammal" % animal""" `range(number)` 返回從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 xx += 1 # x = x + 1 的簡(jiǎn)寫# 用 try/except 塊來處理異常# Python 2.6 及以上適用: try:# 用 raise 來拋出異常raise IndexError("This is an index error") except IndexError as e:pass # pass 就是什么都不做,不過通常這里會(huì)做一些恢復(fù)工作#################################################### ## 4. 函數(shù) ##################################################### 用 def 來新建函數(shù) def add(x, y):print "x is %s and y is %s" % (x, y)return x + y # 通過 return 來返回值# 調(diào)用帶參數(shù)的函數(shù) add(5, 6) # => 輸出 "x is 5 and y is 6" 返回 11# 通過關(guān)鍵字賦值來調(diào)用函數(shù) add(y=6, x=5) # 順序是無所謂的# 我們也可以定義接受多個(gè)變量的函數(shù),這些變量是按照順序排列的 def varargs(*args):return argsvarargs(1, 2, 3) # => (1,2,3)# 我們也可以定義接受多個(gè)變量的函數(shù),這些變量是按照關(guān)鍵字排列的 def keyword_args(**kwargs):return kwargs# 實(shí)際效果: keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}# 你也可以同時(shí)將一個(gè)函數(shù)定義成兩種形式 def all_the_args(*args, **kwargs):print argsprint kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """# 當(dāng)調(diào)用函數(shù)的時(shí)候,我們也可以進(jìn)行相反的操作,把元組和字典展開為參數(shù) args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # 等價(jià)于 foo(1, 2, 3, 4) all_the_args(**kwargs) # 等價(jià)于 foo(a=3, b=4) all_the_args(*args, **kwargs) # 等價(jià)于 foo(1, 2, 3, 4, a=3, b=4)# 函數(shù)在 python 中是一等公民 def create_adder(x):def adder(y):return x + yreturn adderadd_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]# 可以用列表方法來對(duì)高階函數(shù)進(jìn)行更巧妙的引用 [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. 類 ##################################################### 我們新建的類是從 object 類中繼承的 class Human(object):# 類屬性,由所有類的對(duì)象共享species = "H. sapiens"# 基本構(gòu)造函數(shù)def __init__(self, name):# 將參數(shù)賦給對(duì)象成員屬性self.name = name# 成員方法,參數(shù)要有 selfdef say(self, msg):return "%s: %s" % (self.name, msg)# 類方法由所有類的對(duì)象共享# 這類方法在調(diào)用時(shí),會(huì)把類本身傳給第一個(gè)參數(shù)@classmethoddef get_species(cls):return cls.species# 靜態(tài)方法是不需要類和對(duì)象的引用就可以調(diào)用的方法@staticmethoddef grunt():return "*grunt*"# 實(shí)例化一個(gè)類 i = Human(name="Ian") print i.say("hi") # 輸出 "Ian: hi"j = Human("Joel") print j.say("hello") # 輸出 "Joel: hello"# 訪問類的方法 i.get_species() # => "H. sapiens"# 改變共享屬性 Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis"# 訪問靜態(tài)變量 Human.grunt() # => "*grunt*"#################################################### ## 6. 模塊 ##################################################### 我們可以導(dǎo)入其他模塊 import math print math.sqrt(16) # => 4# 我們也可以從一個(gè)模塊中導(dǎo)入特定的函數(shù) from math import ceil, floor print ceil(3.7) # => 4.0 print floor(3.7) # => 3.0# 從模塊中導(dǎo)入所有的函數(shù) # 警告:不推薦使用 from math import *# 簡(jiǎn)寫模塊名 import math as m math.sqrt(16) == m.sqrt(16) # => True# Python的模塊其實(shí)只是普通的python文件 # 你也可以創(chuàng)建自己的模塊,并且導(dǎo)入它們 # 模塊的名字就和文件的名字相同# 也可以通過下面的方法查看模塊中有什么屬性和方法 import math dir(math)

轉(zhuǎn)載于:https://www.cnblogs.com/Zhengxue/p/9977799.html

總結(jié)

以上是生活随笔為你收集整理的python语法学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。