1. import
# -*- coding: utf-8 -*- ## 引入新的包 import turtle import pickle # 檔案操作 import tensorflow as tf # alias tf from time import time, localtime # 引入想要的功能 from time import * # 引入所有功能 ## 引入自定義包: 在Mac系統中,下載的python模塊會被存盤到外部路徑site-packages,同樣,我們自己建的模塊也可以放到這個路徑,最后不會影響到自建模塊的呼叫, """ If the module doesn't exist, pip install name_module # for python2 pip3 install name_module # for python3 pip install name_module=verson_num # for python install specific versions pip3 install name_module=version_num # for python3 specific versions pip install -U name_module # for update pip3 install -U name_module # for update """
2. 輸入
a_input = input('please input a number:') score = int(input('Please input your score: \n'))
3. 輸出
print("hello, world") ## 占位符 ## %d 整數 ## %f 浮點數 ## %s 字串 ## %x 十六進制整數 print('Age: %s. Gender: %s' % (25, True)) # format 占位符 {} print('Hello, {0}, 成績提升了 {1:.1f}%'.format('小明', 17.125))
4. 賦值,運算
### 特殊: 多變數賦值 a, b, c = 1, 2, 3 print(a, b, c) ## 加,減,乘,除,取余,取整, 乘方 ## + , -, * , /, %, // , ** print(2**4) ## 編碼 ord('中') # 獲取字符的整數表示 chr(12321) # 獲取編碼對應的字符 'ABC'.encode('ascii') # 編碼為指定的bytes '中文'.encode('utf-8') b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') # 讀取位元組流封裝 len('ABC') # 計算位元組長度 len('\xe4\xb8\xad\xe6\x96\x87')
5. range使用: 工廠函式
range(1, 10) stop = 10 range(stop=stop) ## it means range(0,10) step = 2 range(1, stop=stop, step=step) # it means range from 1 to 10 step by 2
學習不能只看代碼和教程,更多的是需要自己動手操作,多寫實戰才能快速掌握知識和經驗,這里免費送大家一套2020最新python入門到高級專案實戰視頻教程,可以去小編的Python交流.扣扣.裙 :巴衣久二五寺久寺二(數字的諧音)轉換下可以找到了,還可以跟行業大牛交流討教!
6. 條件陳述句
## python 用縮進表示代碼塊 age = input("input your age\n") if int(age) > 18: print("already 成年") elif int(age) > 30: print("30 more") else: print('<18') print('out of if else ') # A exercise # L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[0][0]) print(L[1][1]) print(L[2][2])
7.回圈陳述句
for i in range(0, 7): print("hello world") # while a<10 and b<20 t = turtle.Pen() for i in range(0, 4): t.forward(100) t.left(90) t = (1, 2) ## while 列印0-9 的資料 ''' while True: print("always print True") ''' conditions = 0 while conditions < 10: print(conditions) conditions += 1
8. 比較操作
比較運算子: 小于(<) 大于 (>) 不大于 (<=) 不小于 (>=) 等于 (==) 不等于 (!=) 會return True 和 False
9. 條件判斷
# 條件 是 非None,非零, 則是True # (list、 tuple 、dict 和 set )集合中,如果元素數量為0 ,則是False age = 20 if age >= 18: print("your age is ", age) print('adult') elif age >= 6: print('teenager') else: print('kid') worked = True isDone = 'Done' if worked else 'not yet' print(isDone)
10. 回圈判斷
for name in c: print(name) print("range 函式生成整數序列 : ", range(4))
continue 和 break
11. 內置集合: list[], tuple()(用圓括號或者不用括號), dict{}, set([])
每個集合都能迭代
11.1 list 串列名 [ 索引地址值 ]
### name[ 1 :5] from 1 ~ 5 ### name[ -1: -2 ] 倒數第二個開始,步長為2 ### list 可變 c = [1, 2, 3, "張三"] c.append("在末尾追加") c.insert(1, "在位置1追加") c.remove(2) # 移除 第一個值為2 的項 c.index(2) # 顯示第一個出現2 的索引 c[2:] # 第二位以及之后的所有的項, 也可以理解為地址為2之后的地址為3以及之后的所有的值 c[-2:] # 串列倒數第二位以及,倒數第二位之后(從左向右)的所有項 c[0:3] # 第0位到第2位(第3位之前)所有項的值 #c.sort() # 默認從小到大, c.sort(reverse=True) # 從大到小排序 print(c[1]) print(c[2:4]) print(c[-1:: -2]) print(" list c 的長度 : %s " % len(c))
11.2多維串列
a = [1 ,2,3,4,5] # 一行五列 multi_dim_a = [[1,2,3], [2,3,4], [3,4,5]] # 三行三列
11.3tuple 元祖 不可變
classmates = ('Michael', 'Bob', 'Tracy') classmates02 = 'Michael', 'Bob', 'Tracy' t = ('a', 'b', ['A', 'B']) t[2][0] = 'X' t[2][1] = 'Y' # t = ('a', 'b', ['X', 'Y'])
11.4 dict ,也就是字典
(其實也就是map),key - value 對應查詢
### key 如果不存在就會報錯 , get() 查詢,不存在則為none ### 特點: ### 查找和插入的速度極快,不會隨著key的增加而變慢; ### 需要占用大量的記憶體,記憶體浪費多, ## dict 是非有序的,需要順序一致的dict, 使用collections模塊中的OrderDict物件 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print("字典: d.get('xx') = d['xx']: ", d.get('Bob')) # 洗掉的兩種方法 d.pop('Bob') del d['Tracy'] d[1] = 20 # 添加的一種方法,直接添加 ## 字典是無序容器,存盤型別多變, d4 = {'apple': [1,2,3], 'pear':{1:3, 3:'a'}, 'orange':func} print(d4['pear'][3]) # a
11.5 set : 自帶去重屬性
## add , remove s = set([1, 2, 3]) s.add(4) print("s.add() ", s) s.remove(4) print("s.remove :: ", s) print("s.pop() ", s.pop()) print("after s.pop()::", s)
12. 迭代器
13. 生成器
14. 定義一個函式
def hi_name(yourname): print(yourname) def hi(yourname, num): print(yourname,num)
14.1 默認引數
## 函式宣告只需要在需要默認引數的地方用 = 號給定即可, 但是要注意所有的默認引數都不能出現在非默認引數的前面 def function_name(price, color='red', brand='carmy', is_second_hand=True): print('price', price, 'color', color, 'brand', brand, 'is_second_hand', is_second_hand, ) hi_name("這是自定義函式的定義輸出")
14.2 自呼叫
''' 如果執行該腳本的時候,該 if 判斷陳述句將會是 True,那么內部的代碼將會執行, 如果外部呼叫該腳本,if 判斷陳述句則為 False,內部代碼將不會執行, ''' if __name__ == '__main__': #code_here print("測驗使用的")
14.3 可變引數
def report(name, *grades): total_grade = 0 for grade in grades: total_grade += grade print(name, 'total grade is ', total_grade) report('wang', 12,14,16,20)
14.4 關鍵字引數
## universal_func(*args, **kw) ==> 可以代表任何函式 def portrait(name, **kw): print('name is', name) for k, v in kw.items(): print(k, v) print(portrait('Mike', age=24, country='China', education='bachelor'))
15. 全域變數
global_param = 100 def for_local(): local_parm = 20 print("value of local_parm is %d" % local_parm) print("value of global_parm is %d" % global_param) # print("local_parm does not exit" % local_parm) print("value of global_parm is %d" % global_param)
16. 檔案操作
''' r 以只讀方式打開檔案,該檔案必須存在, r+ 以可讀寫方式打開檔案,該檔案必須存在, rb+ 讀寫打開一個二進制檔案,只允許讀寫資料, rt+ 讀寫打開一個文本檔案,允許讀和寫, w 打開只寫檔案,若檔案存在則檔案長度清為0,即該檔案內容會消失,若檔案不存在則建立該檔案, w+ 打開可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案內容會消失,若檔案不存在則建立該檔案, a 以附加的方式打開只寫檔案,若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾,即檔案原先的內容會被保留,(EOF符保留) a+ 以附加方式打開可讀寫的檔案,若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾后,即檔案原先的內容會被保留, (原來的EOF符不保留) wb 只寫打開或新建一個二進制檔案;只允許寫資料, wb+ 讀寫打開或建立一個二進制檔案,允許讀和寫, wt+ 讀寫打開或著建立一個文本檔案;允許讀寫, at+ 讀寫打開一個文本檔案,允許讀或在文本末追加資料, ab+ 讀寫打開一個二進制檔案,允許讀或在檔案末追加資料, 轉義字符 輸出 \' ' \" " \a ‘bi’響一聲 \b 退格 \f 換頁(在列印時) \n 回車,游標在下一行 \r 換行,游標在上一行 \t 八個空格(對齊) \\ \ ''' game_data = {"position": "N2 E3", "pocket": ["key", "knife"], "money": 160} save_file = open("save.dat", "wb") ## 其中形式有'w':write;'r':read. pickle.dump(game_data, save_file) save_file.close() ## 關閉檔案 load_file = open("save.dat", "rb") load_game_data = pickle.load(load_file) load_file.read() load_file.readline() # 讀取第一行 load_file.readlines() # python_list 形式 print(load_game_data) load_file.close() for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y)
16.1 for回圈后面還可以加上if判斷,這樣我們就可以篩選出僅偶數的平方:
[x * x for x in range(1, 11) if x % 2 == 0] [m + n for m in 'ABC' for n in 'XYZ'] import os # 匯入os模塊,模塊的概念后面講到 [d for d in os.listdir('.')] # os.listdir可以列出檔案和目錄
16.2 面對物件編程
class Calculator: #首字母要大寫,冒號不能缺 name = 'Good Calculator' #該行為class的屬性 price = 18 def add(self,x,y): print(self.name) result = x + y print(result) def minus(self,x,y): result=x-y print(result) def times(self,x,y): print(x*y) def divide(self,x,y): print(x/y) ''' cal=Calculator() #注意這里運行class的時候要加"()",否則呼叫下面函式的時候會出現錯誤,導致無法呼叫. cal.name cal.add(10,20) ''' # __init__可以理解成初始化class的變數,取自英文中initial 最初的意思.可以在運行時,給初始值附值, # 這里的下劃線是雙下劃線 # # # 運行c=Calculator('bad calculator',18,17,16,15),然后調出每個初始值的值,看如下代碼, class Calculator: name = 'good calculator' price = 18 def __init__(self,name,price,height,width,weight): # 注意,這里的下劃線是雙下劃線 self.name=name self.price=price self.h=height self.wi=width self.we=weight
17. 例外處理
try: file=open('eeee.txt','r') #會報錯的代碼 except Exception as e: # 將報錯存盤在 e 中 print(e)
18. ZIP函式
a=[1,2,3] b=[4,5,6] ab=zip(a,b) print(list(ab)) ## 需要list 來可視化這個功能 for i,j in zip(a,b): print(i/2,j*2)
19. map
def fun(x,y): return (x+y) list(map(fun,[1],[2]))
大家掌握了嗎?如果還沒有掌握的話可以進小編的Python交流.扣扣.裙 :巴衣久二五寺久寺二(數字的諧音轉換下可以找到了)免費領取2020年秋季最新python學習實戰教程和python電子書,裙里還有BAT大牛,可以大牛近距離討論學習,
本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/111788.html
標籤:其他
下一篇:linux配置SOCK5代理
