10分鐘!帶你快速瞭解python編程套路!文末附python資料分享

本文面向對象為具有一丁點編程經驗的小夥伴,旨在快速瞭解Python的基本語法和部分特性。

想領取python學習資料的小夥伴請私信小編(資料)

10分鐘!帶你快速瞭解python編程套路!文末附python資料分享


前言

<code> # Python中單行註釋請用‘#’
""" Python中多行註釋
請用""",我寫不了那麼
多字,隨便湊個樣板。
"""/<code>

1. 基本類型和運算符

<code> # 定義了一個數字 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/<code>

2. 變量和集合

<code> # 打印 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!"/<code>

列表

<code> # 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/<code>

想要更多更詳細的的python教程資料嗎?私信小編(資料)即可領取

元組

<code># 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/<code>

字典

<code># 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/<code>

集合

<code>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/<code>


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 邏輯運算符

<code># 創建一個變量
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/<code>

4. Functions

<code># 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]/<code>

5. Python中的類

<code># 下面代碼是定義了一個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/<code>

6. Python的模塊(庫)

<code># 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/> # folder as your current/> # 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中當前目錄的優先級會高於內置模塊的優先級/<code>

7. Python中的高級特性(生成器、裝飾器:wraps

<code># 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 :/<code>

最後,自學python的小夥伴們注意了!

轉發本文+私信小編“資料”,即可領取小編精心整理的學習資料一份!

10分鐘!帶你快速瞭解python編程套路!文末附python資料分享

10分鐘!帶你快速瞭解python編程套路!文末附python資料分享


分享到:


相關文章: