【Python】第二模塊part1函數、裝飾器、迭代器、內置方法

  • 01-雞湯之人醜就要多讀書
  • 02-三元運算
  • 03-文件處理
  • 04-文件處理-二進制模式
  • 05-文件處理-智能檢測編碼的工具
  • 06-文件處理-寫模式操做文件
  • 07-文件處理-追加模式操做文件
  • 08-文件處理-混合操做文件
  • 09-文件操做其餘功能
  • 10-文件處理-文件修改功能
  • 11-函數-基本介紹
  • 12-函數-默認參數
  • 13-函數-關鍵參數
  • 14-函數-非固定參數
  • 15-函數-非固定參數2
  • 16-函數-返回值
  • 17-函數-局部變量
  • 18-函數-在函數裏修改全局變量
  • 19-函數-在函數裏修改列表數據
  • 20-函數-嵌套函數
  • 21-函數-做用域
  • 22-函數-匿名函數
  • 23-函數-高階函數
  • 24-遞歸介紹
  • 25-遞歸與棧的關係
  • 26-遞歸的做用
  • 27-遞歸的特性總結
  • 28-遞歸的做用
  • 29-尾遞歸優化
  • 30-函數-內置方法1
  • 31-函數-內置方法2
  • 32-函數-內置方法3
  • 33-函數-內置方法4
  • 34-函數-內置方法5
  • 36-函數-函數進階-雞湯
  • 37-函數-函數進階-命名空間
  • 38-函數-函數進階-做用域的查找空間
  • 39-函數-函數進階-閉包
  • 40-函數-函數進階-裝飾器
  • 41-函數-函數進階-裝飾器流程分析
  • 42-函數-函數進階-裝飾器帶參數的函數
  • 43-函數-函數進階-裝飾器帶參數2
  • 44-函數-函數進階-列表生成式
  • 45-函數-函數進階-生成器
  • 46-函數-函數進階-斐波那契數列
  • 47-函數-函數進階-生成器調用方法
  • 48-函數-函數進階-函數寫生成器
  • 49-函數-函數進階-生成器send方法
  • 50-函數-函數進階-迭代器
  • 51-函數-函數進階-做業需求

01-雞湯之人醜就要多讀書;

一、一個好的講師,不光傳授知識,也能給學生帶來心靈上的成長,雞湯也是要喝的;

二、讀書「真的」能夠改變一個的氣質,真的能夠變得有內涵;

三、去豆瓣網上看書評、影評;

給豆瓣圖書打個小廣告——豆瓣圖書TOP250:https://book.douban.com/top250?icn=index-book250-all

四、讀書推薦《追風箏的人》、《白鹿原》;

五、任何有收益的事情,都不是「短平快」獲取來的,「慢」是一種生活姿態;

六、套用錢鍾書夫人楊絳(jiang)的一句話,咱們大多數人的窘境都是:想法太多,讀書太少!

七、咱們的人生Level必定程度上能夠由讀書來決定,由內而外的感知到變化;

八、改變人生的幾種方式:讀書、看電影、去旅行、經歷一些「別樣的」事情;

九、電影推薦——《阿甘正傳》、《辛德勒的名單》;

十、咱們大多數人都不會以爲本身LOW,百分之八十的人都會以爲本身還「湊合」,但實際上結果,你懂得...;

02-三元運算

一、三元運算初識;

三元運算又稱「三目運算」,是對簡單條件語句的簡寫,如:html

03-文件處理

一、咱們你們平常如何操做文件呢;

  • 一、安裝文本編輯器軟件,如windows自帶記事本工具、notepad++;
  • 二、選中鼠標右鍵,利用文本編輯器軟件打開文件;
  • 三、查看 or 寫入內容;
  • 四、保存、關閉;

二、文本的操做分爲讀、寫、修改;

1)讀;python

複製代碼
1 #! /usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #__author__ = "tqtl"
4 # Date:2018/5/14 21:57
5 #f = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='r')#UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 9: illegal multibyte sequence
6 file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='r',encoding='utf-8')#打開文件;
7 file_data = file.read()#閱讀文件內容;
8 print(file_data)#打印文件內容;
9 file.close()#必定要關閉文件;
總結:以什麼樣的編碼格式存儲文件,必定要使用相同的編碼格式打開;
複製代碼

兼職白領學生空姐模特護士的聯繫方式.txt程序員

王心顏 上海 169 46  13813234424
馬纖羽 深圳 173 50 13744234523
喬亦菲 廣州 172 52 15823423525
羅夢竹 北京 175 49 18623423421
劉諾涵 北京 170 48 18623423765
嶽妮妮 深圳 177 54 18835324553
賀婉萱 深圳 174 52 18933434452
葉梓萱 上海 171 49 18042432324
杜姍姍 北京 167 49 13324523342
black girl 河北 167 50 13542342233

04-文件處理-二進制模式

一、那麼問題來了,若是咱們事先不知道文件的編碼格式怎麼辦?!

複製代碼
1 #! /usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #__author__ = "tqtl"
4 # Date:2018/5/14 22:22
5 # E-Mail: tqtl911@163.com
6 file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='rb')#b是binary的縮寫,以二進制的形式打開文件,用於網絡傳輸,給機器看,適用於不知道文件編碼格式的場景;
7 file_data = file.read()#閱讀文件內容;
8 print(file_data)#打印文件內容;
9 file.close()#必定要關閉文件;
複製代碼

05-文件處理-智能檢測編碼的工具

一、chardet工具(動態監測編碼的可能類型);

複製代碼
 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 #__author__ = "tqtl"
 4 # Date:2018/5/14 22:36
 5 # E-Mail: tqtl911@163.com
 6 # Wechat:cxz19930911
 7 #pip 安裝第三方模塊chardet,相似於yum安裝第三方軟件;
 8 
 9 import chardet
10 f = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='rb')
11 data = f.read()
12 print(data)
13 f.close()
14 print(chardet.detect(data))#{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}#0.9表示類似程度;
複製代碼

二、chardet工具的pip安裝;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/19 0019 10:29
 6 import chardet#導入模塊;
 7 file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='rb')
 8 data = file.read()
 9 print(data)
10 print(chardet.detect(data))#{'encoding': 'GB2312', 'confidence': 0.823045267489712, 'language': 'Chinese'}
11 print(data.decode('GB2312'))#解碼操做,顯示中文;
複製代碼
  日誌輸出

06-文件處理-寫模式操做文件

一、如何不佔用所有內存讀取文件內容?!

  • 循環文件,即每次只讀取一部分;
複製代碼
 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 #__author__ = "tqtl"
 4 # Date:2018/5/14 23:04
 5 # E-Mail: tqtl911@163.com
 6 # Wechat:cxz19930911
 7 file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='r',encoding='utf-8')
 8 for lines in file:
 9     print(lines)
10 file.close()
11 # 王心顏    上海 169 46    13813234424
12 #
13 # 馬纖羽     深圳    173    50    13744234523
14 #
15 # 喬亦菲    廣州    172    52    15823423525
16 #
17 # 羅夢竹     北京    175    49    18623423421
18 #
19 # 劉諾涵     北京    170    48    18623423765
20 #
21 # 嶽妮妮     深圳    177    54    18835324553
22 #
23 # 賀婉萱     深圳    174    52    18933434452
24 #
25 # 葉梓萱    上海    171    49    18042432324
26 #
27 # 杜姍姍 北京  167 49 13324523342
28 #
29 # black girl  河北  167 50  13542342233
30 #爲何會有空行,如何消除文件之間的空行?!
31 #No.1文件中自己隱藏着\n換行符;
32 #No.2 print語句自己會換行,因此呈現的效果是換了兩行;
複製代碼

二、寫文件操做;

1 #寫文件操做
2 file = open(file='兼職.txt',mode='w',encoding='utf-8')
3 file.write('北大本科美國留學一次50,微信號:cxz19930911')#write方法;
4 file.close()#注意,必定要關閉文件;

1 file = open(file='兼職write.txt',mode='wb')
2 file.write("路飛學城!".encode('gbk'))
3 file.close()#輸出:路飛學城!
1 file = open(file='兼職write.txt',mode='wb')
2 file.write("原子二號!".encode('gbk'))
3 file.close()#輸出:原子二號!

小結:

一、注意write模式操做文件,永遠都不是修改,而是建立新文件;

二、如若原來文件與新文件名稱相同,就是清空文件內容,再從新寫入新內容;

三、So,使用write時候,必定要慎重!防止把源文件內容清空,過程不可逆;

07-文件處理-追加模式操做文件

一、追加模式,將內容追加至文件的尾部;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/19 0019 18:20
file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='ab')#b表明binary,二進制模式追加;
file.write('\n槓娘 北京 167 55 135585834333'.encode('gbk'))
file.close()#若是不是使用with方法,記得必定要關閉文件;
複製代碼

08-文件處理-混合操做文件

一、混合模式之r+讀寫模式;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/19 0019 18:28
file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='r+',encoding='gbk')#讀寫模式操做文件;
data = file.read()
print("content",data)
file.write("\nnewline 1哈哈")
file.write("\nnewline 2哈哈")
file.write("\nnewline 3哈哈")
file.write("\nnewline 4哈哈")
print("\nnew content",file.read())
file.close()
複製代碼

PS:先讀取內容,而後寫入,再次去讀取,內容在寫入後讀取,因此未打印出來,但文件中的確已經寫入新的內容;

一、混合模式之w+寫讀模式;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/19 0019 18:28

#w+寫讀模式
file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='w+',encoding='gbk')#寫讀模式操做文件;
data = file.read()
print("content",data)
file.write("\nnewline 1哈哈")
file.write("\nnewline 2哈哈")
file.write("\nnewline 3哈哈")
file.write("\nnewline 4哈哈")
print("\nnew content",file.read())
file.close()
複製代碼

總結:

一、r+讀寫模式,即先讀後寫,至關於以「讀」的模式打開,支持向後面追加內容至文件中;web

二、w+寫讀模式,以寫的模式打開,支持讀取,咱們知道,寫模式是以建立的模式打開文件,會把以前的內容先覆蓋掉,而後再寫入,但能夠讀取到後續寫入的內容,使用場景:幾乎用不到;算法

09-文件操做其餘功能

一、文件操做的其餘方法;

1)手工將buffer刷入硬盤中,file.flush()方法;

複製代碼
 1 C:\Users\Administrator\PycharmProjects\LFXC2018\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.3\helpers\pydev\pydevconsole.py" 50524 50525
 2 import sys; print('Python %s on %s' % (sys.version, sys.platform))
 3 sys.path.extend(['C:\\Users\\Administrator\\PycharmProjects\\LFXC2018', 'C:/Users/Administrator/PycharmProjects/LFXC2018'])
 4 PyDev console: starting.
 5 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
 6 file = open(file='file_flush_test.txt',mode='w',encoding='gbk')
 7 file.write('\n測試文件的flush操做')
 8 13
 9 file.write('\n再次測試文件flush操做2')
10 15
11 file.flush()
複製代碼

2)Linux中一切皆文件,在Linux系統中判斷文件的屬性是否可讀,返回值爲布爾值,buffer中的內容不可讀取;

複製代碼
C:\Users\Administrator\PycharmProjects\LFXC2018\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.3\helpers\pydev\pydevconsole.py" 50583 50584
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\\Users\\Administrator\\PycharmProjects\\LFXC2018', 'C:/Users/Administrator/PycharmProjects/LFXC2018'])
PyDev console: starting.
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
file = open(file='file_flush_test.txt',mode='w',encoding='gbk')
file.write('\n測試文件的flush操做')
13
file.write('\n再次測試文件flush操做2')
15
file.flush()
file.readable()
False
複製代碼

三、file.readline()每次只讀一行;

四、seek及tell方法,讀取以及跳轉至制定光標的位置;

seek方法找到的是字符嗎?編程

總結:

一、tell與seek方法是按照字節來讀取內容的,而read是按照字符來讀取;vim

二、具體內容的展現,與編碼格式有關,好比gbk佔2個字節,utf-8佔用3個字節(中文狀況下);c#

五、truncate方法,按照制定長度截斷文件;

10-文件處理-文件修改功能

一、替換模式修改文件;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/19 0019 19:32
file = open(file='兼職白領學生空姐模特護士的聯繫方式.txt',mode='r+',encoding='utf-8')
file.seek(10)
file.write("[路飛學城]luffycity")
file.close()
複製代碼

二、vim與word打開文件的原理說明(硬盤存儲機制與原理決定);

三、既省內存又能讀取大文件的方法——邊讀邊改(不佔內容空間可是讀取過程當中多佔用一份硬盤空間);

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/19 0019 21:29
 6 import os
 7 file_name = "兼職白領學生空姐模特護士的聯繫方式.txt"
 8 file_new_name = "%s.new"%file_name
 9 old_str = "喬亦菲"
10 new_str = "槓娘"
11 file = open(file = file_name,mode='r',encoding='utf-8')
12 file_new = open(file = file_new_name,mode='w',encoding='utf-8')
13 #循環遍歷整個文件;
14 for line in file:#定義臨時變量line
15     if old_str in line:
16         line = line.replace(old_str,new_str)
17     file_new.write(line)
18 file.close()
19 file_new.close()
20 os.rename(file_new_name,'123.txt')
複製代碼
複製代碼
王心顏 [路飛學城]luffycity424
馬纖羽    深圳 173    50 13744234523
喬亦菲    廣州 172    52 15823423525
羅夢竹    北京 175    49 18623423421
劉諾涵    北京 170    48 18623423765
嶽妮妮    深圳 177    54 18835324553
賀婉萱    深圳 174    52 18933434452
葉梓萱    上海 171    49 18042432324
杜姍姍 北京  167 49 13324523342
black girl  河北  167 50  13542342233
複製代碼

練習題

練習題1 —— 全局替換程序:

  • 寫一個腳本,容許用戶按如下方式執行時,便可以對指定文件內容進行全局替換;windows

    `python your_script.py old_str new_str filename` 
  • 替換完畢後打印替換了多少處內容;微信

練習題2 —— 模擬登錄:

  • 用戶輸入賬號密碼進行登錄;
  • 用戶信息保存在文件內;
  • 用戶密碼輸入錯誤三次後鎖定用戶,下次再登陸,檢測到是這個用戶也登陸不了;

11-函數-基本介紹

書籍推薦——JInPIngMei(博客園,不讓使用中文);

一、函數初識;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/19 0019 22:45
def helloworld():#函數名sayhi;
    print("Hello,I'm TQTL.")
print(helloworld)#直接打印是內存地址:<function sayhi at 0x0000020147E219D8>;
helloworld()#經過函數名進行調用;
#函數能夠帶有參數;
def sayhi(name):
    print("Hello",name)
    print("My name is black girl.")
#sayhi()#TypeError: sayhi() missing 1 required positional argument: 'name' 報錯,缺乏位置參數;
sayhi('TQTL')#Hello TQTL

#寫一個計算兩個數的乘方的程序;
a,b = 5,3
c = a**b
print(c)#125;
#使用函數改造以上程序;
def calc(x,y):
    res = x**y
    print(res)
calc(2,10)#1024;
calc(2,5)#32;
#函數的特性:
"""
小結:
一、減小重複代碼,提高程序員的逼格兒;
二、使程序變得可拓展,引用函數的位置,修改一處便可完成擴展操做;
三、使程序變得容易維護,好比以前報警使用郵件,如今改成微信,修改一處便可;
函數,即對功能的封裝;
"""
複製代碼

12-函數-默認參數

一、函數參數的做用;

  • 形參變量;
  • 實參變量;

二、默認參數;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:18/6/30 22:25
""
"""
一、函數參數-形參變量、實參變量;
"""
def stu_register(name,age,country,course):#形參;
     print("學生註冊信息".center(30,'-'))
     print(name,age,country,course)

stu_register("王山炮",22,"CN","Python")#實參;
stu_register("張叫春",21,"CN","Linux")#實參;
stu_register("劉老根",25,"CN","Devops")#實參;
print("兩段程序的分割線".center(40,'#'))

"""
------------學生註冊信息------------
王山炮 22 CN Python
------------學生註冊信息------------
張叫春 21 CN Linux
------------學生註冊信息------------
劉老根 25 CN Devops
################兩段程序的分割線################
"""
#def stu_register(name,age,country = "CN",course):#形參,SyntaxError: non-default argument follows default argument

#引出默認參數;
def stu_register(name,age,course,country = "CN"):#形參;
    print("學生註冊信息".center(30,'*'))
    print(name,age,course,country)

stu_register("王山炮",22,"Python")#不傳實參;
stu_register("張叫春",21,"Linux","JP")#傳了其餘的實參JP;
stu_register("劉老根",25,"Devops","CN")#傳了默認參數CN;
"""
************學生註冊信息************
王山炮 22 Python CN
************學生註冊信息************
張叫春 21 Linux JP
************學生註冊信息************
劉老根 25 Devops CN
"""
# 小結:默認參數必須放在位置參數以後;
複製代碼

13-函數-關鍵參數

一、關鍵參數; 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 11:03
""
"正常狀況下,給函數stu_register傳入參數要按照順序,不想按照順序傳入就可使用關鍵參數,只需指定參數名便可(即指定了參數名的參數就叫作關鍵參數),但關鍵參數必須放在位置參數以後"
def stu_register(name,age,course='PY',country='CN'):#形參下的位置參數
    print("學生註冊信息".center(30,'-'))
    print('姓名:',name)
    print('年齡:',age)
    print('國籍:',country)
    print('課程:',course)

#stu_register("王山炮",course = 'PY',22,country = "JP",)#不能夠這樣表示,course = 'PY'應該在22以後;
#stu_register("王山炮",course = 'PY',22,age=25,country = "JP",);#也不能夠如此表示,由於至關於傳了兩個age參數;
stu_register("王山炮",course = 'PY',age = 22,country = "JP")#此時cousre、age就從位置參數轉變成了關鍵參數;
"""
------------學生註冊信息------------
姓名: 王山炮
年齡: 22
國籍: JP
課程: PY
"""

#關鍵參數的錯誤舉例:
def stu_register(name,age,course,country='CN'):#形參name,age,cource,默認參數:country='CN'
    print("學生註冊信息".center(30,'*'))
    print(name,age,course,country)
stu_register("TQTL",course="Python",age = 22)#默認參數country不填寫;關鍵參數爲course\age能夠打亂順序傳值;
"""
************學生註冊信息************
TQTL 22 Python CN
"""
#stu_register("TQTL",course="Python",22)#SyntaxError: positional argument follows keyword argument
#stu_register("TQTL",23,course="Python",age = 22)#TypeError: stu_register() got multiple values for argument 'age'
複製代碼

14-函數-非固定參數

一、參數能夠傳入多個值的使用場景;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 12:04
""
"""
一、需求:發送報警任務,公司僅有1個運維人員;
"""
def send_alert(msg,users):
    print(msg,users)
send_alert("報警發送給Linux運維工程師:","alex")
"""
一、新需求:發送報警任務,公司已經具有10個運維人員該如何應對?;
"""
def send_alerts(msg,*users,age):
    for u in users:
        print(msg,"報警發送給:",u)
send_alerts("此處是位置參數msg","rain","eric",age=22)
#send_alerts("alex","rain","eric",22)#TypeError: send_alert() missing 1 required keyword-only argument: 'age'
"""
小結:
一、若是參數中出現*users,傳遞的參數就能夠再也不是固定的個數,穿過來的全部參數打包成元組形式;
二、通常不會使用*uers,約定俗成使用*args來表示傳入非固定參數;

"""

#傳入參數的方式一:
send_alerts('發送報警給運維人員1','cuixiaozhao','lijingping','cuixiaoshan',age=28)
send_alerts('發送報警給運維人員2','cuixiaozhao','cuixiaoshan',age=28)
send_alerts('發送報警給運維人員3','cuixiaozhao','lijingping','cuixiaoshan',age=28)
send_alerts('發送報警給運維人員4','cuixiaozhao','lijingping',age=28)

#方式二:
send_alerts('發送報警給運維人員5',*['cuixiaozhao','lijingping','cuixiaoshan','cuixiaosi'],age=28)#列表以前加*號;
"""
報警發送給Linux運維工程師: alex
此處是位置參數msg 報警發送給: rain
此處是位置參數msg 報警發送給: eric
發送報警給運維人員1 報警發送給: cuixiaozhao
發送報警給運維人員1 報警發送給: lijingping
發送報警給運維人員1 報警發送給: cuixiaoshan
發送報警給運維人員2 報警發送給: cuixiaozhao
發送報警給運維人員2 報警發送給: cuixiaoshan
發送報警給運維人員3 報警發送給: cuixiaozhao
發送報警給運維人員3 報警發送給: lijingping
發送報警給運維人員3 報警發送給: cuixiaoshan
發送報警給運維人員4 報警發送給: cuixiaozhao
發送報警給運維人員4 報警發送給: lijingping
發送報警給運維人員5 報警發送給: cuixiaozhao
發送報警給運維人員5 報警發送給: lijingping
發送報警給運維人員5 報警發送給: cuixiaoshan
發送報警給運維人員5 報警發送給: cuixiaosi
""" 
複製代碼

15-函數-非固定參數2

一、字典類型的非固定參數;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 12:10
""
"""
一、**kwargs形式的非固定參數,即字典形式數據;
"""
def user_info(name,*args,**kwargs):#**kwargs接受的是字典形式的數據;
    print(name,args,kwargs)
user_info("TQTL",22,"Model-3","1000ww")#TQTL (22, 'Model3', '1000ww') {},最後一位返回空字典;
user_info("TQTL",22,"Model-3","1000ww",addr="河北省",tel=13811221893)#TQTL (22, 'Model-3', '1000ww') {'addr': '河北省', 'tel': 13811221893}

d = {'degree':'primary school'}
user_info('Peiqi',d)#Peiqi ({'degree': 'primary school'},) {},此時d爲字典形式;
user_info('Peiqi',**d)#Peiqi () {'degree': 'primary school'},字典前面加上**,便可傳參正常;
"""
TQTL (22, 'Model-3', '1000ww') {}
TQTL (22, 'Model-3', '1000ww') {'addr': '河北省', 'tel': 13811221893}
Peiqi ({'degree': 'primary school'},) {}
Peiqi () {'degree': 'primary school'}
"""
複製代碼

16-函數-返回值

一、判斷函數功能是否執行成功;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 12:19
""
"""
一、函數外部的代碼想要獲取函數的執行結果,就能夠在函數裏用return語句把結果返回;
"""
def stu_register(name,age,course='PY',country='CN'):#形參,默認參數爲course,country,位置參數爲name,age;
    print("學生註冊信息".center(30,'-'))
    #print('\n姓名:',name,'\n年齡:',age,'\n國籍:',country,'\n課程:',course)#顯示效果同下方;
    print('姓名:',name)
    print('年齡:',age)
    print('國籍:',country)
    print('課程:',course)

    if age > 22:
        return False
        #return age,name#此處的返回值能夠是任意值,好比False、字符串、列表、元組、字典;默認的函數返回值爲None;
        #print("判斷函數是否結束")#return表明函數的結束,即碰見return就表明函數的結束,未指定就返回None;
    else:
        return True#此處的返回值能夠是任意值;默認的函數返回值爲None
    #return name,age#使用逗號分隔變量名稱;
    #return [name,age]#這種形式也能夠;
registriation_status = stu_register("王山炮",29,course="PY全棧開發",country="JP")
print(registriation_status)#('王山炮', 24),函數只能返回一個值,元組也是一個值;

if  registriation_status:
    print("學生信息註冊成功")
else:
    print("年齡太大,不予註冊學生信息。")
"""
小結:
一、函數在執行過程當中,只要遇到return語句,就會中止執行並返回結果,so能夠理解爲return意味着函數的結束;
二、若是在函數中未指定return語句,那這個函數的返回值爲None。
"""
複製代碼

17-函數-局部變量

一、局部變量初識;

  • 定義在函數外部的一級代碼的變量,叫作全局變量,全局能引用,但遵循「從上到下」的順序;
  • 局部變量,是指定義在函數裏的變量,只能在局部生效;
  • 在函數內部能夠引用全局變量;若是在全局和局部均存在相同變量如name,那麼函數查找變量的順序是「由內而外」的;
複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 12:47
#局部變量初識;
""
"""
一、在函數內部裏面定義的變量爲局部變量,只能局部生效;
二、定義在函數外部一級代碼的變量,叫作全局變量,全局通用使用;
"""
name = "Black Girl"
def change_name():
    name = "黑皮膚的姑娘"
    print("在",name,"裏面,函數內部name變量的內存地址爲:",id(name))

change_name()

print(name,",函數外部name變量的內存地址爲:",id(name))

def modify_name():
    name = "我是非洲的姑娘哦"
    print("在", name, "裏面,函數內部name變量的內存地址爲:", id(name))

modify_name()
print(name,",函數外部name變量的內存地址爲:",id(name))
"""
總結:
一、外部不能夠引用裏面的name變量,裏面能夠引用外部的變量,前提是內部未定義name的狀況下;
二、若是全局和局部均有一個變量叫作name,函數查找變量的順序是由內而外的;
三、定義兩個不一樣的函數如change_name和modify_name,二者是獨立的空間,相同的name變量各自不會影響;
"""
複製代碼

 

18-函數-在函數裏修改全局變量

一、global關鍵字修改局部變量爲全局變量;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 13:15
""
"""
一、在函數裏面修改全局變量,進入global關鍵字,用來聲明變量爲全局變量;
"""
name = "Black Girl"#全局變量
def change_name():
    global name#聲明name變量爲全局變量且位置必須在name以前,global全局的;從實際開發的角度,不建議使用global,
    name = "黑皮膚的姑娘"
    print("在",name,"裏面,函數內部name變量的內存地址爲:",id(name))
change_name()
print(name,",函數外部name變量的內存地址爲:",id(name))
"""
一、由於實際場景中,其餘位置仍是調用全局變量,將函數內部的變量聲明爲全局變量後,函數一執行,即就修改了,後續拍錯難度加大;
"""
複製代碼

 

19-函數-在函數裏修改列表數據

一、修改列表中的數據;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 14:23
""
"""
一、在函數裏修改列表的數據;
"""
#No.01
names = ["Alex","Black girl","Peiqi"]
def change_name():
    #names = ["Alex", "Black girl"]#列表的從新賦值,不生效;總體的內存地址不可修改,可是內部的元素的內存地址可修改;
    del names[2]
    names[1] = "黑姑娘"
    print(names)
change_name()#['Alex', '黑姑娘']
print(names)#['Alex', '黑姑娘']


#No.02
names = ["Alex","Black girl","Peiqi"]

def change_name():
    global names
    names =[12,3,4]#聲明全局變量後,對names變量進行從新賦值操做;
    print(names)
change_name()#[12, 3, 4]
print(names)#[12, 3, 4]
"""
小結:
一、修改整個列表自己的內存地址是不能夠的,可是修改列表中某個元素的內存地址是能夠的;
二、global關鍵字不建議使用;
"""
複製代碼

 

20-函數-嵌套函數

一、嵌套函數初識;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 14:37
""
"""
嵌套函數
一、即函數裏面繼續寫函數;
"""
def func1():
    print("No.01:",'alex')
    def func2():
        print("No.02:",'eric')
    func2()
#Question1:執行func1()#返回結果爲alex
func1()
#Question2:執行func1()#返回結果爲alex;eric
"""
總結:
一、函數內部能夠再次定義函數;
二、函數定義以後,不管是內部仍是外部,須要被調用方能執行;好比func2()語句即調用了函數;
"""

#Question3:執行func3()#返回結果爲73,84,100
age = 19#一級變量age;全局變量
def func3():
    age = 73#二級變量age;局部變量
    print("No.03:",age)
    def func4():
        age = 84#三級變量age;次局部變量;
        print("No.04:",age)
        def func5():
            age = 100
            print("No.05:",age)
        func5()
    func4()
func3()
#小結:變量age會從下往上遞歸查找;

#No.06
age = 19
def func6():
    age = 75
    def func7():
        print("No.06:",age)
    func7()
func6()
#小結:若是子函數內部沒有age變量,會從下往上進行查找,直到找到爲止;

#No.0八、09
age = 19
def func8():
    age = 179#將age移動至函數名func9()上面;
    print("No.08:",age)
    def func9():
        print("No.09:",age)
    age = 79
    age = 88
    func9()
func8()

#No.十、11
# age = 19
# def func10():
#     #age = 79
#     def func11():
#         print("No.11:",age)#NameError: free variable 'age' referenced before assignment in enclosing scope
#     func11()
#     age = 79#將age移動至函數名func11()上面;放在此處;
# func10()
# print(age)
#No.十一、12
age = 19
def func11():
    global age
    #age = 79
    def func12():
        print("No.11:",age)#
    func12()
    age = 79#將age移動至函數名func12()上面;放在此處;
func11()
print("No.12:",age)#此處的age應爲聲明爲global全局變量,因此打印結果爲79

#最難的題-#No.1三、14:
age = 19
def func13():
    global age
    def func14():
        print("No.13:",age)#No.13: 77
    age = 77
    func14()
func13()
print("No.14:",age)#No.14: 77
複製代碼

 

21-函數-做用域

一、函數的做用域初識;

  • 在Python中,一個函數就是一個做用域(JavaScript類似)全部的局部變量放置在其做用域中;
  • 在C#、Java中的做用域爲{};
  • 代碼定義完成後,做用域已經生成,做用域鏈向上查找;
  • 函數名能夠當作返回值;好比return func2;
複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 15:57
""
"""
函數的做用域初識:
一、在Python中,一個函數就是一個做用域;
二、Java、C#中做用域,使用{}來區分做用域的;
三、局部變量放置在其做用域中;
四、代碼定義完成後,做用域已經生成,做用域鏈向上查找;
"""
age = 18
def func1():
    age = 73
    def func2():
        print(age)
    #return 666
    return func2#返回函數名,而非函數名+括號(),
#func1()
val = func1()
#print(val)#666
print(val)#<function func1.<locals>.func2 at 0x000001C159E61EA0>
複製代碼

22-函數-匿名函數

一、匿名函數初識;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 20:00
""
"""
匿名函數:
一、
"""
def calc(x,y):
    if x < y:
        return x * y
    else:
        return x / y
    #return x * y
#func = lambda x,y:x * y#lamda關鍵字來聲明一個匿名函數;
func = lambda x, y:x * y if x < y else x / y#lamda關鍵字結合三元運算來聲明一個匿名函數;
print(calc(3,3))
print(func(3,3))

data = list(range(10))
print(data)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index, i in enumerate(data):
    data[index] = i*i
print(data)#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

#以上程序的優化;
data = list(range(10))
print(data)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

def power(n):#定義一個乘方函數power;
    return n*n

print(list(map(power,data)))#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

print(list(map(lambda x:x*x,data)))#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]#lambda通常和其餘方法聯合使用,好比map;
"""
小結:
一、節省代碼量;
二、代碼質量高;
"""
複製代碼

 

  • 節省代碼量;
  • 逼格兒高超;

23-函數-高階函數

一、高階函數初識;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 20:46
""
"""
高階函數初識:
一、變量能夠指向函數;
二、函數的參數能接收變量,那麼一個函數就能夠接收另外一個函數做爲參數,這種函數就能夠稱之爲'高階函數';
"""
def calc(x):
    return x*x
#func = lambda x:x*x
func = calc#變量名指向函數
func(2)#等價於calc(2)
print(func(2))

def func(x,y):
    return x + y
def calc(x):
    return x
f = calc(func)#calc()此刻就是高階函數;
print(f(5,9))#5 + 9 = 14

def func2(x,y):
    #return abs(x+y)
    return abs,x,y
res = func2(3,-10)
print(res)#(<built-in function abs>, 3, -10)

"""
小結:
"高階函數"只須要知足如下任意一個條件:
一、接收一個或多個函數做爲輸入;
二、return返回另一個函數;
"""
複製代碼

 

24-遞歸介紹

一、遞歸初識(在函數的執行過程當中調用本身);

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 21:58
""
"""
遞歸初識;在函數執行過程當中,調用本身;
"""

import sys#導入sys模塊;
print(sys.getrecursionlimit())#Python中最大值的限制爲1000,防止將內存佔用完畢;
sys.setrecursionlimit(1500)#修改成1500次限制;
def recursion(n):
    print(n)
    recursion(n+1)
recursion(1)#RecursionError: maximum recursion depth exceeded while calling a Python object
#遞歸是循環的一種;Python;
複製代碼

 

25-遞歸與棧的關係

一、我以前也沒明白遞歸這個東西;

http://www.cnblogs.com/alex3714/articles/8955091.html 堆棧掃盲博文分享;

26-遞歸的做用

一、解決數學上的問題;

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 22:14
""
"""
遞歸的做用:
一、用來解決數學中的難題:好比斐波那契數列;
10/2 = 5
5/2= 1
2/2 = 1
"""
def calc(n):
    v = int(n/2)
    if v == 0:#添加一個條件判斷;
        return "Done"
    print(v)
    calc(v)
    print(v)#返回值爲:5\2\1  1\2\5
calc(10)
複製代碼

 

27-遞歸的特性總結

一、一層一層的進入,一層層的退出;

二、遞歸特性總結:

一、遞歸必須有結束條件,要否則就會成爲死循環,最終內存撐爆系統;

二、每進入更深一層時,問題規模相比上次遞歸都有所減小:

三、遞歸的執行效率不過高,遞歸層次過多會致使棧溢出,

28-遞歸的做用

一、能夠用於解決不少算法問題,把複雜的問題分紅一個個小問題,一一解決。

二、好比求斐波那契數列、漢諾塔、多級評論樹、二分查找、求階乘等。用遞歸求斐波那契數列、漢諾塔 對初學者來說可能理解起來不太容易,因此咱們用階乘和二分查找來給你們演示一下。

 

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/20 0020 22:34
""
"""
求階乘:
一、公式:n!=n*(n-1)!
二、n!=1*2*3*4....*n
"""

def factorial(n):
    if n == 1:
        return 1
    return  n * factorial(n-1)
print(factorial(4))#24
複製代碼

 

29-尾遞歸優化

一、尾遞歸初識;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/20 0020 22:43
 6 #經過尾部遞歸來優化遞歸;
 7 def calc(n):
 8     print(n)
 9     return calc(n+1)#尾部遞歸,但在Python中不生效,不節省內存,C語言中存在,使用場景很少;
10 calc(1)#依舊會報錯,RecursionError: maximum recursion depth exceeded while calling a Python object
複製代碼

30-函數-內置方法1

一、Python的內置方法;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/21 0021 21:36
 6 print("abs-絕對值函數:",abs(-11))
 7 #dict,將一些數據轉爲字典類型;
 8 #print(help(int))#Help on class int in module builtins:
 9 numbers = [1,4,5,-1,3]
10 print("min-返回最小值函數:",min(numbers))#返回最小值-1
11 print("max-返回最大值函數:",max(numbers))#返回最大值5
12 
13 print(all([]))#True,全部值爲True才返回True
14 print(any([False,0,-1,1]))#True,有任何一個值爲爲True就返回True
15 
16 print("打印當前程序中的全部變量:",dir())#['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'numbers']
17 
18 print(hex(12))#將十進制數值12轉換爲16進制:0xc
19 
20 #print(help(slice))#不會就help,就像Linux中的man
21 li = list(range(10))
22 print(li)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
23 s = slice(1,7,2)#切片,步長爲2,沒什麼卵用;提起定義切片的規則;
24 print(s)#slice(1, 7, 2)
25 print(li[1:3])#[1,2]
26 print(li[s])#[1, 3, 5]
27 
28 print(divmod(15,6))#(2, 3)返回值爲商和餘數
29 """
30 PyDev console: starting.
31 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
32 10//3
33 3
34 10/3
35 3.3333333333333335
36 10%3
37 1
38 """
39 li = [0, 1, 2, 3, 4, 5,-1,37,33,100,15,16, 7, 8, 9]
40 print(sorted(li))#[-1, 0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 33, 37, 100]
41 dic = {}
42 for a in range(20):
43     dic[a] = a - 50
44 print(dic)#字典自己無序;
45 print(dic.items())#dict_items([(0, -50), (1, -49), (2, -48), (3, -47),
46 print(sorted(dic.items()))#[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45),
47 print(sorted(dic.items(),key = lambda x:x[1]))
48 dic[0] = 399
49 print(sorted(dic.items(),key = lambda x:x[1]))#最大值在最後面;
50 print(sorted(dic.items(),key = lambda x:x[1],reverse=True))#最大值在最前面[(0, 399), (19, -31), (18, -32), (17, -33)
51 
52 s = 'abcd天晴天朗'
53 print(ascii(s))#'abcd\u5929\u6674\u5929\u6717',將字符轉成二進制,沒什麼卵用;
54 
55 #enumerate()枚舉,返回列表的索引;
56 print(oct(12))#0o14,將10進制轉換成爲8進制;
57 print(bin(12))#0b1100,將10進制轉換成爲2進制;
複製代碼

31-函數-內置方法2

一、內置方法2;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/21 0021 22:19
 6 f = "1+3/2"
 7 print(f)#1+3/2
 8 print(eval(f))#eval()函數,將字符串轉成數字,返回值:2.5,只能處理單行代碼;
 9 
10 code = """
11 def foo():
12     prinr("run foo")
13     return 1234
14 foo()
15 """
16 res = eval("1+3+3")
17 res2 = exec("1+3+3")
18 print('res',res)#res 7
19 print('res',res2)#res None
20 """
21 小結:
22 eval只能處理單行代碼,而exec能夠處理多行代碼;
23 但exec沒有返回值,eval有返回值;
24 """
25 
26 print(ord('a'))#返回字符在ASCII碼錶中的位置97;
27 print(ord('b'))#返回字符在ASCII碼錶中的位置98;
28 print(chr(98))#經過ASCII碼錶中的位置,返回字符b
29 print(chr(97))#經過ASCII碼錶中的位置,返回字符a
30 a = [1,4,5,-1,3,0]
31 print(sum(a))#求列表中元素的和;
32 
33 #bytearray
34 a = [1,4,5,-1,3,0]
35 s = 'abcd路飛學城'
36 print(s)#abcd天晴天朗
37 #s[0]='AA'#TypeError: 'str' object does not support item assignment
38 #s = bytearray(s)#TypeError: string argument without an encoding
39 s = s.encode('utf-8')
40 print(s[0])#a在ASCII碼錶中的位置:97
41 #s[0] =98#TypeError: 'bytes' object does not support item assignment
42 s = bytearray(s)
43 print(s[0])#97
44 s[0] = 65
45 print(s)#bytearray(b'Abcd\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe5\x9f\x8e')
46 print(s[4])#232
47 s[4]=233
48 print(s)#bytearray(b'Abcd\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe5\x9f\x8e')
49 print(s.decode())#Abcd鷯飛學城
50 print(id(s))#2166037941024
51 s[0]=66
52 print(id(s))#2166037941024
53 
54 #map filter reduce三劍客;
55 map(lambda x:x*x,[1,2,3,4,5])
56 print(list(map(lambda x:x*x,[1,2,3,4,5])))#[1, 4, 9, 16, 25]
57 print(list(filter(lambda x:x>3,[1,2,3,4,5])))#[4, 5]返回值
58 import functools
59 print(functools.reduce(lambda x,y:x+y,[1,3,4,5,6678,4,2]))#求和:6697
60 print(functools.reduce(lambda x,y:x+y,[1,3,4,5,6678,4,2],3))#求和:6700
61 print(functools.reduce(lambda x,y:x*y,[1,3,4,5,6678,4,2]))#求乘積:3205440
62 
63 print(pow(2,10))#返回2的10次冪;
複製代碼

32-函數-內置方法3

一、內置方法3;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/21 0021 22:54
 6 #print(help(print()))
 7 """
 8 C:/Users\Administrator\PycharmProjects\LFXC2018\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/LFXC2018/文件操做&函數/函數/32-函數-內置方法3.py
 9 Help on NoneType object:
10 class NoneType(object)
11  |  Methods defined here:
12  |  
13  |  __bool__(self, /)
14  |      self != 0
15  |  
16  |  __new__(*args, **kwargs) from builtins.type
17  |      Create and return a new object.  See help(type) for accurate signature.
18  |  
19  |  __repr__(self, /)
20  |      Return repr(self).
21 None"""
22 s = 'Hey, My name is alex\n,from shandong province.'
23 print(s)#默認end結尾是一個\n換行符;
24 '''
25 Hey, My name is alex
26 ,from shandong province.
27 '''
28 print(s,end='||')#
29 '''
30 Hey, My name is alex
31 ,from shandong province.||
32 '''
33 
34 print('\n崔曉昭','李靜瓶',sep='--->')#崔曉昭--->李靜瓶
35 print('崔曉昭','李靜瓶',sep='<---')#崔曉昭<---李靜瓶
複製代碼

33-函數-內置方法4

一、內置方法4;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/21 0021 22:54
 6 #print將內容直接重定向至文件中;
 7 msg = "又回到最初的起點"
 8 f = open(file='那些年.txt',mode='w',encoding='utf-8')
 9 print(msg,"記憶中你青澀的臉。",sep="|",end="",file=f)
10 print(msg,"記憶中你青澀的臉。",sep="|",end="",file=f)
11 #又回到最初的起點|記憶中你青澀的臉。又回到最初的起點|記憶中你青澀的臉。
12 #callable()判斷一個對象是否可調用;
13 a = [1,23]
14 print(callable(a))#False
15 print(vars())#打印當前全部的變量名和變量值;
16 print(locals())#打印函數的局部變量;
17 print(globals())#打印全局變量;
18 b = {1,2,45}
19 print(repr(b))#{1, 2, 45}
20 
21 a = [1,2,3,4,5]
22 b = ['a','b','c','d','e']
23 print(list(zip(a,b)))#[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]使得列表一一對應;
複製代碼

34-函數-內置方法5

一、內置方法5;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/21 0021 23:23
 6 print(complex(3,5))#(3+5j)#變爲複數
 7 print(round(1.553433))#四捨五入取值;
 8 print(round(1.453433))#四捨五入取值;
 9 print(round(1.343433,5))#保留5位小數;
10 #四劍客:delattr(),hasattr(),getattr(),setattr()面向對象時候講述;
11 print(hash("崔曉昭"))#hash值:8836266252390594456;
12 print(set([1,3,4,5,6]))#將列表變爲集合:{1, 3, 4, 5, 6}
複製代碼

36-函數-函數進階-雞湯

一、電影推薦-《荒野求生》

https://v.qq.com/x/cover/4vle2tvyudfpaky.html

二、書籍推薦-《百年孤獨》

https://item.jd.com/12152685.html

37-函數-函數進階-命名空間

一、name space(名稱空間)初識;

1)名稱空間總分3種:

  • locals:是函數內的名稱空間,包括局部變量和形參;
  • globals:全局變量,函數定義所在模塊的名字空間;
  • builtins:內置模塊的名字空間;
複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/23 0023 21:31
""
"""
命名空間:
一、又名name space,即存放變量名與變量值綁定關係的地方;
"""
x = 1
print(globals())#{'__name__': '__main__', '__doc__': '', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001F32965D0F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/TQTL911/PycharmProjects/LFXC2018/第2模塊函數編程/第1章函數、裝飾器、迭代器、內置方法/37-函數-函數進階-命名空間.py', '__cached__': None, 'x': 1}
print(locals())#{'__name__': '__main__', '__doc__': '', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000025D1C6DD0F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/TQTL911/PycharmProjects/LFXC2018/第2模塊函數編程/第1章函數、裝飾器、迭代器、內置方法/37-函數-函數進階-命名空間.py', '__cached__': None, 'x': 1}
print(__builtins__)#<module 'builtins' (built-in)>
print(dir(__builtins__))
"""
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 
'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',
'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 
'GeneratorExit',
'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 
'KeyError', 'KeyboardInterrupt',
'LookupError',
'MemoryError', 'ModuleNotFoundError',
'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 
'OSError', 'OverflowError', 
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 
'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 
'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 
'ValueError', 
'Warning', 'WindowsError', 
'ZeroDivisionError', 
'__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 
'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 
'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr',
'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 
'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
"""
複製代碼

總結:不一樣變量的做用域不一樣,就是由這個變量所在命名空間決定的。

2) 做用域(scope)即範圍:

  • 全局範圍:全局存活,全局有效;
  • 局部範圍:臨時存活,局部有效;

查看做用域的方法——globals(),locals()

複製代碼
 1 C:\Users\Administrator\PycharmProjects\LFXC2018\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.3\helpers\pydev\pydevconsole.py" 63904 63905
 2 import sys; print('Python %s on %s' % (sys.version, sys.platform))
 3 sys.path.extend(['C:\\Users\\Administrator\\PycharmProjects\\LFXC2018', 'C:/Users/Administrator/PycharmProjects/LFXC2018'])
 4 PyDev console: starting.
 5 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
 6 x = 1
 7 globals()
 8 {'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'MemoryError': <class 'MemoryError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
 9 All Rights Reserved.
10 Copyright (c) 2000 BeOpen.com.
11 All Rights Reserved.
12 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
13 All Rights Reserved.
14 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
15 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
16     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x0000019EBE74D840>, 'runfile': <function runfile at 0x0000019EBE273EA0>, '_': None}, 'sys': <module 'sys' (built-in)>, 'x': 1}
17 locals()
18 {'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'MemoryError': <class 'MemoryError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
19 All Rights Reserved.
20 Copyright (c) 2000 BeOpen.com.
21 All Rights Reserved.
22 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
23 All Rights Reserved.
24 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
25 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
26     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x0000019EBE74D840>, 'runfile': <function runfile at 0x0000019EBE273EA0>, '_': None}, 'sys': <module 'sys' (built-in)>, 'x': 1}
27 __buildins__
28 Traceback (most recent call last):
29   File "<input>", line 1, in <module>
30 NameError: name '__buildins__' is not defined
31 __builtins__
32 {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'MemoryError': <class 'MemoryError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
33 All Rights Reserved.
34 Copyright (c) 2000 BeOpen.com.
35 All Rights Reserved.
36 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
37 All Rights Reserved.
38 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
39 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
40     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x0000019EBE74D840>, 'runfile': <function runfile at 0x0000019EBE273EA0>, '_': None}
41 dir(__builtins__)
42 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
複製代碼

38-函數-函數進階-做用域的查找空間

一、做用域的查找順序;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/23 0023 21:49
 6 #做用域的查找空間
 7 n = 10
 8 def func():
 9     n = 20#局部變量;
10     print("func:",n)
11     def func2():
12         n = 30
13         print("func2:",n)
14         def func3():
15             print("func3:",n)
16         func3()#func3: 30
17     func2()#func2: 30
18 func()#func: 20
19 """
20 做用域的查找順序LEGB;一層一層往上查找;
21 L:locals#局部的;是函數內的名字空間,包括局部變量和形參;
22 E:enclosing#相鄰的上一級;外部嵌套函數的名字空間;
23 G:globals#全局的;全局變量,函數定義所在模塊的名字空間;
24 B:builtins#內置的;內置模塊的名字空間;name space;
25 """
複製代碼

39-函數-函數進階-閉包

一、閉包的概念;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/23 0023 21:59
""
"""
閉包:
一、概念性的東西;
二、閉包的意義:返回的函數對象,不只僅是一個函數對象,在該函數外還包裹了一層做用域,這使得,該函數不管在何處調用,優先使用本身外層包裹的做用域;
"""
def func():
    n = 10
    def func2():
        print("func2:",n)
    #func2()
    return  func2#返回func2的內存地址;
f = func()
print(f)#<function func.<locals>.func2 at 0x000002B0D5A91AE8>
f()#按常理來說,執行完func()函數後,func2()已經釋放掉了,可是它存在返回值;func2: 10
#以上就是閉包的概念;
#在外部拿到了內部的函數,而且還可使用內部函數的做用域裏面的值;
複製代碼

 

40-函數-函數進階-裝飾器

一、裝飾器是Python基礎中的最重要知識點;http://www.cnblogs.com/alex3714/articles/5765046.html

41-函數-函數進階-裝飾器流程分析

一、裝飾器初識;

複製代碼
  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 # __Author__:Administrator
  4 # Version:python3.6.5
  5 # Date:2018/5/23 0023 22:13
  6 # _*_coding:utf-8_*_
  7 """
  8 user_status = False  # 用戶登陸了就把這個改爲True;
  9 def login():
 10     _username = "alex"  # 僞裝這是DB裏存的用戶信息;
 11     _password = "abc!23"  # 僞裝這是DB裏存的用戶信息;
 12     global user_status
 13     if user_status == False:
 14         username = input("user:")
 15         password = input("pasword:")
 16         if username == _username and password == _password:
 17             print("welcome login....")
 18             user_status = True#用戶登陸了,把這個改爲True;
 19         else:
 20             print("wrong username or password!")
 21     else:
 22         print("用戶已登陸,驗證經過...")
 23 
 24 
 25 def home():
 26     print("---首頁----")
 27 def america():
 28     login()  # 執行前加上驗證;
 29     print("----歐美專區----")
 30 def japan():
 31     print("----日韓專區----")
 32 def henan():
 33     login()  # 執行前加上驗證;
 34     print("----河南專區----")
 35 home()
 36 america()
 37 henan()
 38 """
 39 
 40 """
 41 封閉:已實現的功能代碼塊不該該被修改;
 42 開放:對現有功能的擴展開放;
 43 """
 44 user_status = False  # 用戶登陸了就把這個改爲True;
 45 def login(func):#把要執行的模塊從這裏傳進來
 46     _username = "alex"  # 僞裝這是DB裏存的用戶信息;
 47     _password = "abc!23"  # 僞裝這是DB裏存的用戶信息;
 48     global user_status
 49     if user_status == False:
 50         username = input("user:")
 51         password = input("pasword:")
 52         if username == _username and password == _password:
 53             print("welcome login....")
 54             user_status = True#用戶登陸了,把這個改爲True;
 55         else:
 56             print("wrong username or password!")
 57     else:
 58         print("用戶已登陸,驗證經過...")
 59     if user_status == True:
 60         func()
 61 
 62 
 63 def home():
 64     print("---首頁----")
 65 def america():
 66     #login()  # 執行前加上驗證;
 67     print("----歐美專區----")
 68 def japan():
 69     print("----日韓專區----")
 70 def henan():
 71     #login()  # 執行前加上驗證;
 72     print("----河南專區----")
 73 home()#首頁不須要認證登陸,
 74 login(america)#america專區,須要驗證,因此調用 login,把須要驗證的功能 當作一個參數傳給login
 75 #america()
 76 login(henan)#america專區,須要驗證,因此調用 login,把須要驗證的功能 當作一個參數傳給login
 77 
 78 #思路繼續優化中;
 79 def plus(n):
 80     return n+1
 81 plus(6)
 82 plus2 = lambda n:n+1
 83 
 84 #繼續解釋;
 85 def login(func):  # 把要執行的模塊從這裏傳進來;
 86     def inner():  # 再定義一層函數;
 87         _username = "alex"  # 僞裝這是DB裏存的用戶信息;
 88         _password = "abc!23"  # 僞裝這是DB裏存的用戶信息;
 89         global user_status
 90         if user_status == False:
 91             username = input("user:")
 92             password = input("pasword:")
 93             if username == _username and password == _password:
 94                 print("welcome login....")
 95                 user_status = True
 96             else:
 97                 print("wrong username or password!")
 98         if user_status == True:
 99             func()  # 看這裏看這裏,只要驗證經過了,就調用相應功能;
100     return inner  # 用戶調用login時,只會返回inner的內存地址,下次再調用時加上()纔會執行inner函數;
複製代碼

42-函數-函數進階-裝飾器帶參數的函數

一、帶裝飾器的參數;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/24 0024 7:03
 6 #最終代碼;
 7 user_status = False  # 用戶登陸了就把這個改爲True;
 8 def login(func):  # 把要執行的模塊從這裏傳進來;
 9     def inner(*args, **kwargs):  # 使用非固定參數;
10         _username = "alex"  # 僞裝這是DB裏存的用戶信息;
11         _password = "abc!23"  # 僞裝這是DB裏存的用戶信息;
12         global user_status
13         if user_status == False:
14             username = input("user:")
15             password = input("pasword:")
16             if username == _username and password == _password:
17                 print("welcome login....")
18                 user_status = True
19             else:
20                 print("wrong username or password!")
21         if user_status == True:
22             #func(args,kwargs) # 使用非固定參數;
23             func(args,kwargs) # 使用非固定參數,支持多個參數;
24     return inner  # 用戶調用login時,只會返回inner的內存地址,下次再調用時加上()纔會執行inner函數;
25 
26 def home():
27     print("---首頁----")
28 @login
29 def america():
30     # login() #執行前加上驗證
31     print("----歐美專區----")
32 @login
33 def japan():
34     print("----日韓專區----")
35 # @login
36 def henan(style):
37     '''
38     :param style: 喜歡看什麼類型的,就傳進來
39     :return:
40     '''
41     # login() #執行前加上驗證
42     print("----河南專區----",style)
43 home()
44 # america = login(america) #你在這裏至關於把america這個函數替換了
45 henan = login(henan)
46 #那用戶調用時依然寫
47 america()
48 henan("3p")#傳入了參數;
49 japan()#不須要傳入參數;
複製代碼

43-函數-函數進階-裝飾器帶參數2

一、裝飾器帶參數2;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/24 0024 7:25
 6 user_status = False  # 用戶登陸了就把這個改爲True
 7 def login(auth_type):#再包括一層在外面;
 8     def outer(func):# 把要執行的模塊從這裏傳進來
 9         def inner(*args, **kwargs):  # 使用非固定參數
10             _username = "alex"  # 僞裝這是DB裏存的用戶信息
11             _password = "abc!23"  # 僞裝這是DB裏存的用戶信息
12             global user_status
13             if user_status == False:
14                 username = input("user:")
15                 password = input("pasword:")
16                 if username == _username and password == _password:
17                     print("welcome login....")
18                     user_status = True
19                 else:
20                     print("wrong username or password!")
21             else:
22                 print("用戶已登陸,驗證經過...")
23             if user_status == True:
24                 #func(args,kwargs) # 使用非固定參數,錯誤
25                 func(*args,**kwargs) # 使用非固定參數,支持多個參數;TypeError: 'str' object is not callable
26         return inner  # 用戶調用login時,只會返回inner的內存地址,下次再調用時加上()纔會執行inner函數
27     return outer
28 def home():
29     print("---首頁----")
30 def america():
31     print("----歐美專區----")
32 #@login('WeChat')
33 def japan():
34     print("----日韓專區----")
35 @login('QQ')
36 def henan(style):
37     print("----河南專區----",style)
38 #henan = login('qq')
39 #print(henan)#<function login.<locals>.outer at 0x00000272E80880D0>
40 # xx = login('qq')
41 # print(xx)
42 # henan = xx(henan)
43 # print(henan)
44 henan("3p")#傳入了參數;
45 #print(r)#<function login.<locals>.outer.<locals>.inner at 0x00000272E8088048>
46 #TypeError: 'str' object is not callable
複製代碼

44-函數-函數進階-列表生成式

一、列表生成式初識;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/26 0026 16:36
#列表生成式
"""
如今有個需求,看列表[0,1,2,3,4,5,6,7,8,9],要求把列表中的每一個值增長1,如何實現?
如何實現?
"""
#二逼青年版本;
a = list(range(10))
print(a)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = []
for i in a:
    b.append(i+1)
print(b)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = b#將b列表賦值給a列表;
print("二逼青年版本:",a)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#普通青年版
a = list(range(10))
print(a)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index,i in enumerate(a):
    a[index] += 1#經過索引增長值
print("普通青年版本:",a)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#文藝青年版
a = list(range(10))
print(a)
a = map(lambda x:x+1,a)#使用lambda匿名函數;
print("文藝青年版:",a)#文藝青年版: <map object at 0x0000018A392D09E8>
for i in a:
    print(i)

#裝逼青年版(引出列表生成式概念)
a = list(range(10))#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = [i+1  for i in a  ]#此處的寫法就是列表生成式;
print(a)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

b = list(range(10))#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [i if i < 5 else i*i  for i in b]#內部使用了「三元運算」
print(b)#[0, 1, 2, 3, 4, 25, 36, 49, 64, 81]

#既能夠循環元組,字典,還能夠循環字符串;
name = "lijingping"
name = [i for i in name]#['l', 'i', 'j', 'i', 'n', 'g', 'p', 'i', 'n', 'g']
print(name)
name = [i*2 for i in name]#字符串能夠「相乘」
print(name)#['ll', 'ii', 'jj', 'ii', 'nn', 'gg', 'pp', 'ii', 'nn', 'gg']

name = "lijingping"#字符串能夠「相加」
name = [i+"cxz" for i in name]
print(name)#['lcxz', 'icxz', 'jcxz', 'icxz', 'ncxz', 'gcxz', 'pcxz', 'icxz', 'ncxz', 'gcxz']
複製代碼

45-函數-函數進階-生成器

一、受到機器內存的限制,列表不能無限制大,好比生成100w個數字;

二、經過「工廠生產器皿」的案例,引入「生成器」的概念;generator-生成器;

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/26 0026 17:01
""
"""
如何生成一百萬個杯子?!
"""
#以生產100萬個杯子(器皿)舉例,引入「生成器」的概念;
numbers = [i for i in range(1000)]
print(numbers)#生成100個數字的列表 numbers 中;
#生成器寫法;
numbers2 = (i for i in range(8))#注意此處與「列表生成式」的區別,使用的是圓括號,爲方便記憶,本人將之命名爲「元組生成式」即生成器!類比元組等價於「只讀列表」的概念;
print(numbers2)#<generator object <genexpr> at 0x0000019298BDF5C8>
#開始生產數據
print(next(numbers2))#0
print(next(numbers2))#1
print(next(numbers2))#2
print(next(numbers2))#3
print(next(numbers2))#4
print(next(numbers2))#5
print(next(numbers2))#6
print(next(numbers2))#7
#print(next(numbers2))#StopIteration,到這裏就再也不生產;
#經過以上來看,是一個一個的生產;而 numbers 則是具有生產「1000」個器皿的能力,但不佔用內存空間大小;
#但只能按照「序號」來生產;只能向前,向前,不能後退後退!generator即生成器;
"""
特性總結:
一、從0開始生產;
二、不能後退,只能向前;
三、經過next(numbers)方法進行生產;
"""
複製代碼
  • numbers2 = (i for i in range(8))#注意此處與「列表生成式」的區別,使用的是圓括號,爲方便記憶,本人將之命名爲「元組生成式」即生成器!類比元組等價於「只讀列表」的概念;
  • print(numbers2)#<generator object <genexpr> at 0x0000019298BDF5C8>#存在內存中,生成器;

46-函數-函數進階-斐波那契數列

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/26 0026 17:16
 6 ""
 7 """
 8 上節咱們學會了"生成器",雖然節省了內存空間,可是使用過程當中不能一直print(next(numbers2)),如此效率就過低下了;
 9 so,咱們可使用for循環或者while循環來打印「生成器」中的數據;
10 """
11 # a = (i for i in range(10))#生成器對象a
12 # for l in a:
13 #     print(l)#for循環,不會出StopIteration
14 #a = (i for i in range(10))
15 # while True:
16 #      next(a)#StopIteration
17 
18 # print(range(100))#range(0, 100)
19 
20 """
21 #range就是生成器的原理生成的;
22 下面咱們瞭解一下,在Python3與Python2中range的區別;
23 一、Python2 中,range(100),以下所示:
24 C:Users\Administrator>python2
25 Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
26 Type "help", "copyright", "credits" or "license" for more information.
27 >>> range(100)
28 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
29 >>>
30 
31 二、Python3中,range則是生成器,以下所示:
32 C:Users\Administrator>python
33 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
34 Type "help", "copyright", "credits" or "license" for more information.
35 >>> range(100)
36 range(0, 100)#不會佔用內存;
37 >>>
38 
39 三、那麼問題來了,Python2中,如何用生成器方式表示range呢?
40 C:Users\Administrator>python2
41 Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
42 Type "help", "copyright", "credits" or "license" for more information.
43 >>> xrange(1000000)
44 xrange(1000000)
45 >>>
46 總結:Python2中的xrange(1000)等價於Python3中的range(1000)
47 """
48 #斐波那契數列;
49 """
50 斐波那契數列(Fibonacci sequence),又稱黃金分割數列、因數學家列昂納多·斐波那契(Leonardoda Fibonacci)以兔子繁殖爲例子而引入,故又稱爲「兔子數列」,指的是這樣一個數列:一、一、二、三、五、八、1三、2一、3四、……....
51 這個數列從第3項開始,每一項都等於前兩項之和。
52 """
53 def fibo(max):
54     n,a,b = 0,0,1#新引入的賦值方法;
55     while n < max:
56         print(b)
57         a,b = b,a+b#將b的值賦值給a,同時將a+b的值賦值給b;
58         n += 1
59     return 'done'
60 fibo(10)#1 1 2 3 5 8 13 21 34 55
61 
62 #經過斐波那契數列,引出yield關鍵字;
63 def fibo(max):
64     n,a,b = 0,0,1#新引入的賦值方法;
65     while n < max:
66         print("before yield.")
67         yield b#yield的做用,把函數的執行過程凍結在這一步而且把b的值返回給外面的next()方法;
68         print(b)
69         a,b = b,a+b#將b的值賦值給a,同時將a+b的值賦值給b;
70         n += 1
71     return 'done'
72 #fibo(10)
73 #print(fibo(10))#<generator object fibo at 0x0000024EE92AF5C8>
74 #經過返回值判斷,此時的fibo就是生成器;
75 f = fibo(10)#將功能轉換成一個「生成器」
76 next(f)
77 next(f)
78 next(f)
79 """
80 小結:
81 引出yield的做用:
82 一、yield把函數的執行過程凍結在這一步;
83 二、此時能夠把b的值,返回給外面的next()方法;
84 三、函數名添加(),內部代碼不執行,只是生成一個生成器對象;
85 能夠把函數執行過程當中的每個狀態,返回到外面來;原來的函數只能在裏面打印,不能往外返回值,以return函數就終止了;
86 """
複製代碼

47-函數-函數進階-生成器調用方法

一、生成器的調用方法;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/26 0026 18:08
 6 # a = (i for i in range(10))
 7 # while True:
 8 #     print(next(a))#while循環會拋出異常,但咱們尚未學習異常處理方法,因此返回值StopIteration
 9 #for循環方法:
10 a = (i for i in range(10))# 生成器;
11 for i in a:
12     print(i)#通常會用for循環方法,且省去了next;
13 #以上的for循環等價於以下,由於在Python3中的range底層就是生成器;:
14 for i in range(100):
15     print(i)
16 """
17 小結:
18 In Python2:
19 range == list;
20 xrange(100000) == 生成器;
21 
22 In Python3:
23 range == 生成器;
24 xrange == 不存在了;
25 """
複製代碼

48-函數-函數進階-函數寫生成器

一、生成器的建立方式;

  • 列表生成式方法(),只能寫一個「三元運算」:
  • 經過函數建立生成器;
複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/26 0026 18:18
 6 #本身經過函數寫range生成器;
 7 # def range2(n):
 8 #     count = 0
 9 #     while count < n:
10 #         print(count)
11 #         count += 1
12 # range2(10)#函數內部執行;
13 #把函數range2作成生成器,只須要一步之遙;
14 def range2(n):
15     count = 0
16     while count < n:
17         print("count",count)
18         count += 1
19         yield count#相似於return,yield使程序凍結,next才解凍!
20 range2(10)#函數調用了,可是沒有返回結果;由於引入了yield關鍵字;
21 print(range2(10))#<generator object range2 at 0x00000254BAAFF5C8>
22 new_range = range2(10)
23 r1 = next(new_range)
24 print(r1)
25 r2 = next(new_range)
26 print(r2)
27 #除了使用next()方法外,還可使用new_range.__next__()
28 new_range.__next__()#返回值count 2
29 """
30 小結:
31 yield vs return
32 一、return 返回並終止function;
33 二、yield 會返回數據並凍結當前的執行過程;
34 三、next方法喚醒凍結的函數執行過程,繼續執行,直到遇到下一個yield;
35 """
36 """
37 生成器的牛逼之處在於:
38 一、以前的函數,從調用起,就必須等待執行結果結束,並返回計算值;
39 二、生成器能夠把函數整個運行過程當中的結果,返回至外面;爲何叫作yield,是暫停的意思,歐洲路牌就是標記這個單詞;
40 """
複製代碼

49-函數-函數進階-生成器send方法

一、生成器中next()方法與send()方法的區別;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/26 0026 18:47
 6 def range2(n):
 7     count = 0
 8     while count < n:
 9         print("count",count)
10         count += 1
11         sign = yield count#相似於return,yield使程序凍結,next才解凍!
12         if sign == 'stop':
13             break
14         print("---sing",sign)
15     return 3333#實驗證實,函數中有了yield 就不會被執行;
16 #range2(3)#函數調用了,可是沒有返回結果;
17 #print(range2(3))#<generator object range2 at 0x00000254BAAFF5C8>
18 new_range = range2(3)
19 next(new_range)
20 print("作了一些其餘的事情,此時還剩餘2次,可是我想終止後面的兩次,如何操做?")
21 #此時還剩餘2次,可是我想終止後面的兩次,如何操做?
22 new_range.send("stop")
23 #send方法的做用:
24 #一、喚醒並繼續執行;next方法只能喚醒;
25 #二、發送一個信息到生成器內部;
26 """
27 函數有了yield以後:
28 一、函數名稱加(),就獲得了一個生成器;
29 二、return 在生成器裏表明生成器的終止,直接報錯;
30 """
複製代碼

50-函數-函數進階-迭代器

一、迭代器Iterator;

複製代碼
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/26 0026 19:04
 6 #迭代能夠理解爲循環;
 7 ""
 8 """
 9 迭代器:
10 咱們已經知道,能夠直接做用與for 循環的數據類型有如下幾種:
11 一類是集合數據類型,好比list、tuple、dict、set、str等;
12 一類是generator,包括生成器和帶yield的generator function;
13 這些能夠直接做用於for循環的對象統稱爲可迭代對象,Iterable;
14 可使用isinstance()判斷一個對象是不是Iterable對象:
15 """
16 from collections import Iterable
17 print(Iterable)
18 print(isinstance('abc',Iterable))#True#字符串;
19 print(isinstance([],Iterable))#True#列表;
20 print(isinstance((),Iterable))#True#元組;
21 print(isinstance({},Iterable))#True#字典;
22 print(isinstance((i for i in range(10)),Iterable))#True
23 print(isinstance(100,Iterable))#False
24 """
25 #生成器不但能夠做用於for循環,還能夠被next()函數不斷調用並返回一個值,直到最後拋出StopIteration錯誤表示沒法繼續返回下一個值了;
26 #能夠被next()函數調用並不斷返回下一個值的對象成爲迭代器:Iterator;
27 #可使用isinstance()判斷一個對象是不是Iterator對象,生成器只是迭代器的一種;
28 """
29 print('-------------------------------')
30 from collections import Iterator
31 print(Iterator)#<class 'collections.abc.Iterator'>
32 print(isinstance('abc',Iterator))#False
33 print(isinstance([],Iterable))#True
34 print(isinstance((),Iterable))#True
35 print(isinstance({},Iterable))#True
36 print(isinstance((i for i in range(10)),Iterator))#True
37 print(isinstance(100,Iterable))#False
38 """
39 生成器都是Iterator對象,但list、dict、str雖然是Iterable,卻不是Iterator;
40 把list、dict、str等Iterable變成Iterator可使用iter()函數;
41 
42 
43 咱們可能會問起,爲何list、dict、str等數據類型不是Iterator?
44 這是由於Python的Iterator對象表示的是一個「數據流」,Iterator對象能夠被next()函數調用並不斷返回
45 下一個數據,直到沒有數據時候拋出異常StopIteration錯誤。能夠把這個數據看作是一個有序序列,
46 但咱們卻不能提早知道序列的長度,只能不斷經過next()函數實現按需計算下一個數據,因此
47 Iterator的計算是「惰性的」,只有在須要返回下一個數據時他纔會計算。
48 
49 當前的階段,generator與Iterator基本是一致的。
50 
51 總結:
52 一、凡是可做用於for循環的對象都是Iterable類型;
53 一、凡是可做用於next()函數的對象都是Iterator類型,他們表示一個惰性計算的序列;
54 三、集合數據類型如list、dict、str等都是Iterable但不是Iterator,不過能夠經過iter()函數得到一個Iterator對象。
55 四、Python3的for循環本質上就是經過不斷調用next()函數實現的,例如:
56 """
57 # for x in [1,2,3,4,5]:
58 #     pass
59 # #等價於
60 it = iter([1,2,3,4,5])
61 #循環
62 while True:
63     try:
64         x = next(it)
65     except StopIteration:#注意冒號不能丟;
66         break
複製代碼

51-函數-函數進階-做業需求

複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/27 0027 8:37
""
"""
本章總節
練習題
文件處理相關
編碼問題

請說明python2 與python3中的默認編碼是什麼?
爲何會出現中文亂碼?你能列舉出現亂碼的狀況有哪幾種?
如何進行編碼轉換?
#-*-coding:utf-8-*- 的做用是什麼?
解釋py2 bytes vs py3 bytes的區別
文件處理
r和rb的區別是什麼?
解釋一下如下三個參數的分別做用
open(f_name,'r',encoding="utf-8")
函數基礎:
寫函數,計算傳入數字參數的和。(動態傳參)
寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操做;
寫函數,檢查用戶傳入的對象(字符串、列表、元組)的每個元素是否含有空內容。
寫函數,檢查傳入字典的每個value的長度,若是大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
解釋閉包的概念

函數進階:
寫函數,返回一個撲克牌列表,裏面有52項,每一項是一個元組
例如:[(‘紅心’,2),(‘草花’,2), …(‘黑桃A’)]
寫函數,傳入n個數,返回字典{‘max’:最大值,’min’:最小值}

例如:min_max(2,5,7,8,4)
返回:{‘max’:8,’min’:2}
寫函數,專門計算圖形的面積

其中嵌套函數,計算圓的面積,正方形的面積和長方形的面積
調用函數area(‘圓形’,圓半徑) 返回圓的面積
調用函數area(‘正方形’,邊長) 返回正方形的面積
調用函數area(‘長方形’,長,寬) 返回長方形的面積
def area():
    def 計算長方形面積():
        pass

    def 計算正方形面積():
        pass

    def 計算圓形面積():
        pass
寫函數,傳入一個參數n,返回n的階乘

例如:cal(7)
計算7*6*5*4*3*2*1
編寫裝飾器,爲多個函數加上認證的功能(用戶的帳號密碼來源於文件),要求登陸成功一次,後續的函數都無需再輸入用戶名和密碼

生成器和迭代器
生成器和迭代器的區別?
生成器有幾種方式獲取value?
經過生成器寫一個日誌調用方法, 支持如下功能

根據指令向屏幕輸出日誌
根據指令向文件輸出日誌
根據指令同時向文件&屏幕輸出日誌
以上日誌格式以下

2017-10-19 22:07:38 [1] test log db backup 3
2017-10-19 22:07:40 [2]    user alex login success 
#注意:其中[1],[2]是指自日誌方法第幾回調用,每調用一次輸出一條日誌
代碼結構以下

 def logger(filename,channel='file'):
    """
  #  日誌方法
   ##  :param channel: 輸出的目的地,屏幕(terminal),文件(file),屏幕+文件(both)
  #  :return:
"""
    ...your code...

 #調用
 log_obj = logger(filename="web.log",channel='both')
 log_obj.__next__()
 log_obj.send('user alex login success')
內置函數
用map來處理字符串列表,把列表中全部人都變成sb,比方alex_sb

name=['alex','wupeiqi','yuanhao','nezha']
用filter函數處理數字列表,將列表中全部的偶數篩選出來

num = [1,3,5,6,7,8]
以下,每一個小字典的name對應股票名字,shares對應多少股,price對應股票的價格

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
計算購買每支股票的總價

用filter過濾出,單價大於100的股票有哪些

一、請分別介紹文件操做中不一樣的打開方式之間的區別:

模式    含義
r    
rb    
r+    
rb+    
w    
wb    
w+    
wb+    
a    
ab    
a+    
ab+
二、有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 請將以字母「a」開頭的元素的首字母改成大寫字母;

三、有以下程序, 請給出兩次調用show_num函數的執行結果,並說明爲何:

   num = 20

   def show_num(x=num):
       print(x)

   show_num()

   num = 30

   show_num()
四、有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 請以列表中每一個元素的第二個字母倒序排序;

五、有名爲poetry.txt的文件,其內容以下,請刪除第三行;

   昔人已乘黃鶴去,此地空餘黃鶴樓。

   黃鶴一去不復返,白雲千載空悠悠。

   晴川歷歷漢陽樹,芳草萋萋鸚鵡洲。

   日暮鄉關何處是?煙波江上令人愁。
六、有名爲username.txt的文件,其內容格式以下,寫一個程序,判斷該文件中是否存在"alex", 若是沒有,則將字符串"alex"添加到該文件末尾,不然提示用戶該用戶已存在;

   pizza
   alex
   egon
七、有名爲user_info.txt的文件,其內容格式以下,寫一個程序,刪除id爲100003的行;

   pizza,100001
   alex, 100002
   egon, 100003
八、有名爲user_info.txt的文件,其內容格式以下,寫一個程序,將id爲100002的用戶名修改成alex li;

   pizza,100001
   alex, 100002
   egon, 100003
九、寫一個計算每一個程序執行時間的裝飾器;

十、lambda是什麼?請說說你曾在什麼場景下使用lambda?

十一、題目:寫一個搖骰子游戲,要求用戶壓大小,賠率一賠一。

要求:三個骰子,搖大小,每次打印搖骰子數。

做業
現要求你寫一個簡單的員工信息增刪改查程序,需求以下:

固然此表你在文件存儲時能夠這樣表示

1,Alex Li,22,13651054608,IT,2013-04-01
2,Jack Wang,28,13451024608,HR,2015-01-07
3,Rain Wang,21,13451054608,IT,2017-04-01
4,Mack Qiao,44,15653354208,Sales,2016-02-01
5,Rachel Chen,23,13351024606,IT,2013-03-16
6,Eric Liu,19,18531054602,Marketing,2012-12-01
7,Chao Zhang,21,13235324334,Administration,2011-08-08
8,Kevin Chen,22,13151054603,Sales,2013-04-01
9,Shit Wen,20,13351024602,IT,2017-07-03
10,Shanshan Du,26,13698424612,Operation,2017-07-02
1.可進行模糊查詢,語法至少支持下面3種查詢語法:

find name,age from staff_table where age > 22

find * from staff_table where dept = "IT"

find * from staff_table where enroll_date like "2013"
2.可建立新員工紀錄,以phone作惟一鍵(即不容許表裏有手機號重複的狀況),staff_id需自增

語法: add staff_table Alex Li,25,134435344,IT,2015-10-29
3.可刪除指定員工信息紀錄,輸入員工id,便可刪除

語法: del from staff_table where  id=3
4.可修改員工信息,語法以下:

UPDATE staff_table SET dept="Market" WHERE  dept = "IT" 把全部dept=IT的紀錄的dept改爲Market
UPDATE staff_table SET age=25 WHERE  name = "Alex Li"  把name=Alex Li的紀錄的年齡改爲25
5.以上每條語名執行完畢後,要顯示這條語句影響了多少條紀錄。 好比查詢語句 就顯示 查詢出了多少條、修改語句就顯示修改了多少條等。

注意:以上需求,要充分使用函數,請盡你的最大限度來減小重複代碼!
"""
相關文章
相關標籤/搜索