Excel2016打印預(yù)覽表格的教程是什么(excel2016怎么看打印預(yù)覽)">Excel2016打印預(yù)覽表格的教程是什么(excel2016怎么看打印預(yù)覽)
774
2022-05-30
注:文章的附件中有兩本學(xué)習(xí)python經(jīng)典書籍的pdf文檔
Python編程環(huán)境設(shè)置
一、sublime Text
1.sublime REPL插件安裝
(1)安裝
先打開插件安裝面板:ctrl+shift+P
輸入install ,選擇Package Control:Install Package
提示安裝成功后重新按ctrl+shift+P,選擇Package Control:Install Package
之后輸入sublimeREPL點(diǎn)擊安裝
在tools中能夠找到sublimeREPL說明安裝成功
(2)配置快捷鍵
首先點(diǎn)擊首選項(xiàng)prefrence
其次打開快捷鍵設(shè)置keybindings
輸入以下代碼后關(guān)閉并保存
{"keys":["f5"], "caption":"SublimeREPL:Python - RUN current file", "command":"run_existing_window_command", "args":{ "id":"repl_python_run", "file":"config/Python/Main.sublime-menu"}}
此舉是將快捷鍵設(shè)置為F5
2.中文設(shè)置
(1)打開安裝好的的sublime,選擇Preferences下面的Package Contorol選項(xiàng)出現(xiàn)彈窗方框
在彈窗輸入install package,選擇對應(yīng)(默認(rèn)第一個(gè))點(diǎn)擊進(jìn)入
(2)在彈窗出輸入chinese,選擇插件ChineseLocaloztions(默認(rèn)第一個(gè))點(diǎn)擊安裝
(3)等待安裝完成,出現(xiàn)中文字體,一般出現(xiàn)就算安裝完成了
(4)此時(shí)可在Help下面的Language處自由切換成簡體中文語言
(5)切換之后的效果,就可以使用中文版了
二、PyCharm相關(guān)
1.中文設(shè)置
安裝 PyCharm 中文插件,打開菜單欄 File,選擇 Settings,然后選 Pulgins,點(diǎn) Marketplace,搜索 chinese,然后點(diǎn)擊 install 安裝
2.安裝注意
3.創(chuàng)建項(xiàng)目時(shí)注意
創(chuàng)建項(xiàng)目
這里選擇Create New Project,會(huì)出現(xiàn)設(shè)置項(xiàng)目名稱和選擇解釋器:
選擇解釋器
注意:這里默認(rèn)使用的 Python 的虛擬環(huán)境,如果你不使用虛擬環(huán)境,一定要修改。
如果出現(xiàn) Interpreter field is empty 表示 Python 的環(huán)境變量有問題。當(dāng)然我們也可以直接選擇,請看下面。
選擇圖中 1,如果 3 位置的下來中選不到 Python.exe, 則點(diǎn)擊 2 位置按鈕。
選擇Python
選擇圖中1, 如果 3 位置依然沒有出現(xiàn) Python.exe,則點(diǎn)擊 2 位置按鈕選擇 Python 的安裝目錄,找到你安裝的 Python 目錄,然后選擇 Python.exe。
然后點(diǎn)擊Create即可。
那么現(xiàn)在項(xiàng)目就創(chuàng)建成功了
項(xiàng)目界面
在上圖中,去掉Show tips on startup,不用每次都打開歡迎界面,然后關(guān)閉即可。
4.創(chuàng)建 Python 文件
在項(xiàng)目名稱的位置點(diǎn)擊鼠標(biāo)右鍵,選擇New > Python File
新建Python文件
輸入文件名稱,點(diǎn)擊 OK 即可。
在文件中輸入代碼:
然后在文件中任意空白位置點(diǎn)擊鼠標(biāo)右鍵,選擇運(yùn)行:
運(yùn)行Python
在界面的下方,顯示 Python 代碼的運(yùn)行結(jié)果
第2節(jié).變量和簡單數(shù)據(jù)類型
2.1變量的命名和使用:
變量名只能包含字母、數(shù)字和下劃線。不能包含空格。
不要將python關(guān)鍵字和函數(shù)名作為變量名
應(yīng)使用小寫的python變量名
同時(shí)給多個(gè)變量賦值
x,y,z=1,2,3
2.2字符串的處理(用引號括起的都是字符串)
方法的應(yīng)用
name= "ada lovelace" print(name) print(name.title()) #首字母大寫,常用于打印名字 print(name.upper()) #全部大寫 print(name.lower()) #全部小寫
字符串的拼接
first_name="ada" last_name="lovelace" full_name=f"{first_name}{last_name}" #將first_name與last_name拼接 print(f"Hello,{full_name.title()}!") #將hello與經(jīng)過方法title處理的名字拼接
2.3轉(zhuǎn)義字符
制表符
print("python") print("\tpython")
換行符
print("c++") print("\nc++")
2.4刪除空白
best_language=" python " print(best_language) print(best_language.lstrip()) #lstrip()方法刪除字符串開頭的空白 print(best_language.rstrip()) #rstrip()方法刪除字符串末尾的空白 print(best_language.strip()) #strip()方法刪除字符串兩頭的空白
2.5數(shù)
將任意兩個(gè)數(shù)相除時(shí),得到的結(jié)果總是浮點(diǎn)數(shù)
書寫很大的數(shù)時(shí),可以使用下劃線將其中的數(shù)字分組,運(yùn)行時(shí)下劃線不會(huì)被打印
number=14_000_000_000_000 print(number)
數(shù)據(jù)類型轉(zhuǎn)換
Str 將其他類型轉(zhuǎn)換成字符串
Bool 將其他類型轉(zhuǎn)換成布爾型
Int 將其他類型轉(zhuǎn)換成整型(若是浮點(diǎn)型則會(huì)保留整數(shù)部分)
Float 將其他類型轉(zhuǎn)換成浮點(diǎn)型
money=1000 print((float(money))) #將字符串類型的1000轉(zhuǎn)換為浮點(diǎn)型的1000.0
2.6將數(shù)據(jù)輸出到文件中
fp=open('E:' , 'a+') #a+為輸出格式 print('I love you.' , file=fp) fp.close()
第3節(jié)列表以及遍歷
3.1列表的特性:有序,元素可以重復(fù),可以存放多種類型
注:索引是從0開始(開頭起始)
也可以從-1開始(結(jié)尾起始)
3.2修改、添加和刪除元素
修改
motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles[0]='ducati' #將motorcycles中索引為0的honda修改為ducati print(motorcycles)
附加
motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles.append('ducati') #在列表末尾添加元素ducati print(motorcycles)
也可用創(chuàng)建一個(gè)空列表,再一個(gè)個(gè)添加元素
插入
motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles.insert(0,'ducati') #在索引為0的元素前面添加元素ducati print(motorcycles)
刪除
根據(jù)索引刪除元素但不可使用它
motorcycles=['honda','yamaha','suzuki'] print(motorcycles) del motorcycles[1] #刪除索引為1的元素 print(motorcycles)
刪除列表末尾的元素并使用它(彈出元素)
popped_motorcycle=motorcycles.pop() #定義被方法pop()刪除的元素 print(motorcycles) #打印原列表 print(popped_motorcycle) #打印被刪除的元素
根據(jù)值刪除元素并使用它的值(彈出元素)
motorcycles=['honda','yamaha','suzuki','ducati'] too_exepensive='ducati' #定義要?jiǎng)h除的元素 motorcycles.remove(too_exepensive) #刪除被定義的元素 print(motorcycles) #打印原列表 print(f"\nA{too_exepensive.title()} is too expensive for me") #將被刪除的元素插入句子中并換行打印這個(gè)句子
3.3組織列表(在并非所有值都是小寫時(shí),按字母排序要復(fù)雜一點(diǎn))
使用sort()方法對列表永久排序(按字母順序排序)
cars=['bmw','audi','toyota','subaru'] cars.sort() print(cars)
按與字母順序相反的順序排列元素(向sort()方法傳遞函數(shù)reverse=True)
cars=['bmw','audi','toyota','subaru'] cars.sort(reverse=True) print(cars)
使用函數(shù)sorted()對列表臨時(shí)排序(字母順序)
print("\nHere is the sorted list:") print(cars) print("\nHere is the original list again:") print(cars)
倒著打印列表
cars=['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars)
確定列表的長度
cars=['bmw','audi','toyota','subaru'] len(cars) #列表長度用列表元素的個(gè)數(shù)表示 print(len(cars))
3.4遍歷整個(gè)列表
magicians=['alice','david','carolina'] for magician in magicians: #(1) #for循環(huán)語句重復(fù)執(zhí)行(1)和(2)的代碼行 print(magician) #(2)
3.5創(chuàng)建數(shù)值列表
使用函數(shù)range()
for value in range(1,6): #會(huì)循環(huán)打印出1,2,3,4,5 print(value) for value in range(7): #只指定一個(gè)參數(shù)時(shí),會(huì)從0開始打印 print(value) numbers=list(range(1,5)) #使用函數(shù)list()將range()的結(jié)果直接轉(zhuǎn)化為列表 print(numbers) even_numbers=list(range(2,11,2)) #第2個(gè)2是指定的步長,此時(shí)range函數(shù)會(huì)從2開始然后不斷加2直到等于或超過終值 print(even_numbers)
函數(shù)range()可以創(chuàng)建幾乎任何需要的數(shù)集
squares=[] for value in range(1,11): square=value **2 #對value的每一個(gè)值進(jìn)行乘方運(yùn)算 squares.append(square) #將每一個(gè)運(yùn)算后的值加入到空白列表中去 print(squares)
對數(shù)字進(jìn)行簡單的統(tǒng)計(jì)計(jì)算
digits=[1,2,3,4,5,6,7,8,9,0] min(digits) #求出列表中的最小值 print((min(digits))) max(digits) #求出列表中的最大值 print((max(digits))) sum((digits)) #求和 print(sum(digits))
列表解析
列表解析將for循環(huán)和創(chuàng)建新元素的代碼合并成一行,并自動(dòng)附加新元素
squares=[value2 **2 for value2 in range(1,11)] print(squares)
3.6多維容器(多種形式的容器和數(shù)據(jù)類型可以共存于一個(gè)列表)
list_a=[32,423,523,324,123,54,67,'Jack'] list_b=['Job', 'Bob', 'Steven',123,8656] #二維列表 list_x=[[1,7,4,9,4],list_a,list_b,'Kin',54,(7,43,2,98),8] #多維列表 print(list_x) print(list_x[1]) #打印列表list_X中索引為1元素 print((list_x[0][3])) #打印列表list_x中索引為0的元素中的索引為3的子元素
3.7使用列表的一部分
切片
要?jiǎng)?chuàng)建切片,可指定要使用的第一個(gè)元素和最后一個(gè)元素的索引
players=['charles','martina','michael','florence','eli'] print(players[0:4])
也可以通過負(fù)數(shù)索引來打印末尾的任意切片
players=['charles','martina','michael','florence','eli'] print(players[-3:])
如果沒有指定第一個(gè)索引,python將自動(dòng)從列表開頭開始
也可以在方括號內(nèi)指定第三個(gè)值,這個(gè)值用來告訴python在指定范圍內(nèi)每隔多少個(gè)元素提取一個(gè)
遍歷切片
遍歷列表的部分元素,可以在for循環(huán)中使用切片
players=['charles','martina','michael','florence','eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title())
復(fù)制列表
要想復(fù)制列表,可創(chuàng)建一個(gè)包含整個(gè)列表的切片
players=['charles','martina','michael','florence','eli'] players2=players[:] print(players2)
3.8元組(相當(dāng)于不可更改的列表,使用圓括號來標(biāo)識)
定義元組
dimensions=(200,50) print(dimensions[0]) print(dimensions[1])
嚴(yán)格意義上來講,元組是由逗號標(biāo)識的,哪怕定義一個(gè)只有一個(gè)元素的元組,也要在這個(gè)元素末尾加上逗號
例如my_t=(3,)
遍歷元組中的所有值
dimensions=(200,50) for dimension in dimensions: print(dimension)
給儲(chǔ)存元組的變量賦值
dimensions=(200,50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions=(400,100) print("\nModified dimensions:") for dimension in dimensions: print(dimension)
第4節(jié).if語句
4.1 if語句的簡單示例
cars=['audi','bmw','subaru','toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title())
4.2 if語句
if-else語句
age=17 if age>=18: print("You are old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry,you are too young to vote.") print("Please register to vote as soon as you turn 18!")
if-elif-else結(jié)構(gòu)
用于檢查超過兩個(gè)的情形
''' 我們以一個(gè)根據(jù)年齡收費(fèi)的游樂場為例: 4歲以下免費(fèi) 4~18歲收費(fèi)25美元 18(含)歲以上收費(fèi)40美元 ''' age=12 if age <4: print("Your admission cost is $0") elif age < 18: #只會(huì)執(zhí)行通過測試的代碼 print("Your admission cost is $25") else: print("Your admission cost is $40") #現(xiàn)在我們將上面的代碼進(jìn)行簡化 age =12 if age <4: price=0 elif age <18: price=25 else: price=40 print(f"Your admission cost is ${price}.") #else代碼塊可以省略,只要不滿足if或elif的測試條件,else中的代碼就會(huì)執(zhí)行 #如果知道最終要測試的條件,就可以考慮用一個(gè)elif代碼塊代替else代碼塊 #if-elif-else結(jié)構(gòu)功能強(qiáng)大,但僅適合用于只有一個(gè)條件滿足的情況,遇到了通過測試的情況,剩下的代碼就會(huì)跳過執(zhí)行
測試多個(gè)條件
requested_toppings=['mushrooms','extra cheese'] if 'mushrooms' in requested_toppings: print('Adding mushrooms.') if 'pepperoni' in requested_toppings: print('Adding pepperoni.') if 'extra cheese' in requested_toppings: print('Adding extra cheese.') print("\nFinished making your pizza!") #首先創(chuàng)建一個(gè)列表,然后依次檢查某一元素是否在列表中最后輸出結(jié)果 #如果只想執(zhí)行一個(gè)代碼塊,就是用if-elif-else結(jié)構(gòu);如果要執(zhí)行多個(gè)代碼塊,使用一系列獨(dú)立的if語句
4.3使用if語句檢查列表
檢查特殊元素
requested_toppings=['nushrooms','green peppers','extra cheese'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Soory we are out of green peppers!") else: print(f"Adding {requested_topping}") print(f"\nFinished making your pizza!")
確定列表不是空的
運(yùn)行for循環(huán)前確定列表是否為空很重要
requested_toppings=[] if requested_toppings: for requested_topping in requested_toppings: print(f"Adding {requested_topping}") print ("\nFinished making your piaaz!") else: print("Are you sure want a plain pizza?")
使用多個(gè)列表:
available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] requested_toppings = ['mushrooms','french fris','extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print(f"Adding {requested_topping}") else: print(f"Sorry,we don't have {requested_topping}") print("\nFinished making your pizza!")
第5節(jié).字典
5.1一個(gè)簡單的字典
字典的特性:無序,鍵對值,鍵不可重復(fù)
alien_0={'color':'green','points':'5'} print(alien_0['color']) #每一個(gè)值對應(yīng)一個(gè)鍵,用于快速查找 print(alien_0['points']) #字典中可以包含任意鍵對值
5.2使用字典
添加鍵對值
alien_0={'color':'green','points':'5'} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 0 print(alien_0)
在空字典中添加鍵對值
alien_0={} alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0)
修改字典中的值
aalien_0={'color':'green'} print(f"The alien is {alien_0['color']}.") ##?。?!注意此處的點(diǎn)和括號!??! alien_0['color']=['yellow'] print(f"The alien is now {alien_0}.")
刪除鍵對值
alien_0={'color':'green','points':'5'} print(alien_0) del alien_0['points'] print(alien_0)
長字典的構(gòu)成
favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python' }
使用get()來訪問值
alien_0={'color':'green','speed':'slow'} point_value=alien_0.get('points','No point value assigned.') print(point_value) #方法get()的第一個(gè)參數(shù)用于指定鍵,第二個(gè)參數(shù)為指定的鍵不存在時(shí)要返回的值,若沒有指定則返回none #如果指定的鍵有可能不存在,應(yīng)考慮使用方法get()
5.3遍歷字典
遍歷所有鍵對值
user_0={ 'username':'efermi', 'first':'enrico', 'last':'fermi' } for key,value in user_0.items(): #items()方法:以列表返回可遍歷的(鍵,值)元組數(shù)組 print(f"\nkey:{key}") print(f"value:{value}")
5.4集合
特點(diǎn):無序,元素不重復(fù),本質(zhì)上是只有鍵的字典
集合的運(yùn)算
set1={123,43,525,63,643,436} set2={45,55,66,87,123,63,58} print(set1&set2) #獲取交集 print(set1|set2) #獲取并集 print(set1-set2) #獲取差集
條件測試
檢查是否相等(檢查時(shí)區(qū)分大小寫)
car = 'Audi' car=='audi' car = 'Audi' car.lower()=='audi'
檢查是否不相等
requested_topping='mushrooms' irequested_topping!='anchovies'
數(shù)值比較
age=18 age==18: age=18 age<21: age >=5: age=18 age<=21: age >=5:
##使用and或or檢查多個(gè)條件
#使用and時(shí),如果至少一個(gè)測試沒有通過,整個(gè)表達(dá)式為Flas #使用or時(shí),至少有一個(gè)條件滿足就能通過整個(gè)測試 age_0=21 age_1=18 age_0>=21 and age_1>=21 age_0=21 age_1=18 age_0>=21 or age_1>=21
檢查特值是否包含在列表中
requested_toppings=['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings 'banana' in requested_toppings banned_users=['andrew','carolina','david'] 'marie' not in banned_users
布爾表達(dá)式
game_active=True can_edit=Flase
條件測試
檢查是否相等(檢查時(shí)區(qū)分大小寫)
car = 'Audi' car=='audi' car = 'Audi' car.lower()=='audi'
檢查是否不相等
requested_topping='mushrooms' irequested_topping!='anchovies'
數(shù)值比較
age=18 age==18: age=18 age<21: age >=5: age=18 age<=21: age >=5:
##使用and或or檢查多個(gè)條件
#使用and時(shí),如果至少一個(gè)測試沒有通過,整個(gè)表達(dá)式為Flas #使用or時(shí),至少有一個(gè)條件滿足就能通過整個(gè)測試 age_0=21 age_1=18 age_0>=21 and age_1>=21 age_0=21 age_1=18 age_0>=21 or age_1>=21
檢查特值是否包含在列表中
requested_toppings=['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings 'banana' in requested_toppings banned_users=['andrew','carolina','david'] 'marie' not in banned_users
布爾表達(dá)式
game_active=True can_edit=Flase
第6節(jié).用戶輸入和while循環(huán)
6.1函數(shù)input()
簡單的輸入
massage=input("Tell me something,and I will repeat it back to you:") print(massage)
輸入數(shù)值
age=input("How old are you?") print(age) #此時(shí)用戶輸入會(huì)被默認(rèn)解釋為字符串 age=input("How old are you?") age=int(age) #此時(shí)就將用戶輸入指定成了數(shù)值 print(age) #更加簡便的指定用戶輸入 age=int(input("How old are you?")) print(int(age))
6.2求模運(yùn)算符
A=4%3 print(A) #將兩個(gè)數(shù)相除并返回余數(shù)
6.3while循環(huán)
while循環(huán)簡介
current_number=1 while current_number<=5: #循環(huán)從1數(shù)到5 print(current_number) current_number +=1
讓用戶選擇何時(shí)退出
prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " message="" #使用空字符定義變量,用于接收輸入的字符串 while message != 'quit': message=input(prompt) print(message)
上述代碼的缺點(diǎn)是將quit也打印了出來,下面用一個(gè)if語句優(yōu)化它
prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " message="" while message != 'quit': message=input(prompt) if message !='quit': print(message)
使用標(biāo)志
prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " active=True while active: message=input(prompt) if message=='quit': active=False else: print(message)
使用break函數(shù)退出循環(huán)
prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " while True: city=input(prompt) if city == 'quit': break #break語句也可以用于退出遍歷列表或字典的for循環(huán) else: print(f"I'd love to go to {city.title()}")
在循環(huán)中使用continue
current_number=0 while current_number <10: current_number += 1 if current_number%2==0: continue print(current_number)
當(dāng)程序陷入無限循環(huán)時(shí),按CTRL+C可以關(guān)閉程序
6.4使用while循環(huán)處理列表和字典
在列表之間移動(dòng)元素
#首先,創(chuàng)建一個(gè)待驗(yàn)證用戶列表 #和一個(gè)用于存儲(chǔ)已驗(yàn)證用戶的空列表 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] #驗(yàn)證每個(gè)用戶,直到?jīng)]有未驗(yàn)證用戶為止 #將每個(gè)經(jīng)過驗(yàn)證的列表都移到已驗(yàn)證用戶列表中 while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) #將元素添加到已驗(yàn)證列表中 #顯示所有已驗(yàn)證的用戶 print("\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())
刪除為特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
使用用戶輸入來填充字典
responses = {} #設(shè)置一個(gè)標(biāo)志,指出調(diào)查是否繼續(xù) polling_active = True while polling_active: #提示輸入被調(diào)查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") #將答卷存儲(chǔ)在字典中 responses[name] = response #看看是否還有人要參與調(diào)查 repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False #調(diào)查結(jié)束,顯示結(jié)果 print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
第7節(jié).函數(shù)
7.1定義函數(shù)
定義一個(gè)打印問候語的函數(shù)
def greet_user(): '''顯示簡單的問候語''' print("Hello") #def關(guān)鍵字告訴python,我要定義一個(gè)函數(shù)
向函數(shù)傳遞信息
def greet_user(username): '''顯示簡單的問候語''' print(f"Hello,{username.title()}!") greet_user('jesse') #函數(shù)被調(diào)用時(shí)被傳達(dá)參數(shù)jesse #上面函數(shù)中的username就是一個(gè)形參 #jesse就是一個(gè)實(shí)參
7.2傳遞實(shí)參
實(shí)參的順序與形參的順序要相同
位置實(shí)參
def describe_pet(animal_type,pet_name): '''顯示寵物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('hamster','harry') #當(dāng)你想再描述一個(gè)寵物時(shí),只需要再調(diào)用一次函數(shù)即可
關(guān)鍵字實(shí)參
關(guān)鍵字實(shí)參是傳遞給函數(shù)的名稱值對
def describe_pet(animal_type,pet_name): '''顯示寵物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet(animal_type='hamster',pet_name='harry') #在調(diào)用函數(shù)時(shí),明確指出各實(shí)參所對應(yīng)的形參
默認(rèn)值
編寫函數(shù)時(shí),可以給每個(gè)形參指定默認(rèn)值
def describe_pet(animal_type,pet_name='harry'): '''顯示寵物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('hamster') #定義函數(shù)時(shí)指定了一個(gè)形參的默認(rèn)值,所以調(diào)用函數(shù)時(shí)只需要指定另一個(gè)形參所對應(yīng)的實(shí)參
7.3返回值
def get_formatted_name(first_name,last_name): '''返回整潔的姓名''' full_name=f"{first_name} {last_name}" return full_name.title() musician=get_formatted_name('jimi','hendrix') print(musician) #此方法可以用于存儲(chǔ)和調(diào)用大量的姓名
使實(shí)參變成可選的
def get_formatted_name(first_name,mid_name,last_name): '''返回整潔的姓名''' full_name=f"{first_name} {mid_name} {last_name}" return full_name.title() musician=get_formatted_name('john','lee','hooker') print(musician) #上面的代碼在指定2個(gè)實(shí)參時(shí)無法運(yùn)行 def get_formatted_name(first_name,mid_name,last_name=''): '''返回整潔的姓名''' full_name=f"{first_name} {mid_name} {last_name}" return full_name.title() musician2=get_formatted_name('john','lee') #當(dāng)函數(shù)的實(shí)參是三個(gè)值而你只指定了2個(gè)時(shí)函數(shù)不會(huì)執(zhí)行,此時(shí)可以將函數(shù)的一個(gè)實(shí)參指定為空值 print(musician2) #上面的代碼在指定2個(gè)實(shí)參時(shí)可以運(yùn)行 #可以將上面的兩種情況合并如下,使其變成可選的 def get_formatted_name(first_name,last_name,middle_name=''): '''返回整潔的姓名''' if middle_name: full_name=f"{first_name} {middle_name} {last_name}" else: full_name=f"{first_name} {last_name}" return full_name.title() musician=get_formatted_name('john','hooker') print(musician) musician=get_formatted_name('john','lee','hooker') print(musician)
返回字典
函數(shù)可以返回任何類型的值,包括字典,列表等復(fù)雜的數(shù)據(jù)結(jié)構(gòu)
def build_person(first_name,last_name): '''返回一個(gè)字典,其中包含有關(guān)一個(gè)人的信息''' person={'first':first_name,'last':last_name} return person musician=build_person('jimi','hendrix') print(musician) #下面擴(kuò)展這個(gè)函數(shù): def build_person(first_name,last_name,age=None): '''返回一個(gè)字典,其中包含有關(guān)一個(gè)人的信息''' person={'first':first_name,'last':last_name} if age: person['age']=age return person musician=build_person('jimi','hendrix',age=27) print(musician)
結(jié)合用函數(shù)和while循環(huán)
def get_formatted_name(first_name,last_name): '''返回整潔的姓名''' full_name=f"{first_name} {last_name}" return full_name.title while True: print("\nPlease tell me your name:") print("(enter 'q' at any time to quit)") f_name=input("First name:") if f_name=='q': break l_name=input("Last name") if l_name=='q': break formatted_name=get_formatted_name(f_name,l_name) print(f"\nHello,{formatted_name}!") #while循環(huán)讓用戶輸入姓名,依次輸入名和性
傳遞列表
將列表傳遞給函數(shù)后,函數(shù)就能直接訪問其內(nèi)容
def greet_users(names): '''向列表中的每位用戶發(fā)出簡單的問候''' for name in names: msg=f"Hello,{name.title()}" print(msg) usernames=['hannah','ty','margot'] greet_users(usernames)
在函數(shù)中修改列表
#首先創(chuàng)建一個(gè)列表,其中包含一些要打印的設(shè)計(jì)。 unprinted_designs=['phone case','robot pendant','dodecahedron'] completed_models=[] #模擬打印每個(gè)設(shè)計(jì),直到?jīng)]有未打印的設(shè)計(jì)為止。 #打印每個(gè)設(shè)計(jì)后,都將其移到列表completed_models中 while unprinted_designs: current_design=unprinted_designs.pop() print(f"Printing model:{current_design}") completed_models.append(current_design) #顯示打印好的所有模型 print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_models) '''為了重新組織上述代碼,我們可以編寫兩個(gè)函數(shù)''' def print_models(unprinted_designs,completed_models): """ 模擬打印每個(gè)設(shè)計(jì),直到?jīng)]有未打印的設(shè)計(jì)為止 打印每個(gè)設(shè)計(jì)后,都將其移到列表completed_models中 """ while unprinted_designs: current_design=unprinted_designs.pop() print(f"Printing model:{current_design}") completed_models.append(current_design) def show_completed_models(completed_models): """顯示打印好的所有模型""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) unprinted_designs=['phone case','robot pendant','dodecahedron'] completed_models=[] print_models(unprinted_designs,completed_models) show_completed_models(completed_models)
禁止函數(shù)修改列表(向函數(shù)傳遞列表的副本而非原件)
print_models(unprinted_designs[:],completed_models)
7.4傳遞任意數(shù)量的實(shí)參
def make_pizza(*toppings): """打印顧客點(diǎn)的所有配料""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese') #形參名中的*讓python創(chuàng)建一個(gè)名為toppings的空元組,并將收集到的所有值都封裝到這個(gè)元組中
結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參
def make_pizza(size,*toppings): """概述要制作的比薩""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"-{topping}") make_pizza(6,'pepperoni') make_pizza(12,'mushrooms','green peppers','extra cheese') #通用形參名*args也收集任意數(shù)量的位置實(shí)參
使用任意數(shù)量的關(guān)鍵字實(shí)參
def build_profile(first,last,**user_info): """創(chuàng)建一個(gè)字典,其中包含我們知道的有關(guān)用戶的一切""" user_info['first_name']=first user_info['last_name']=last return user_info user_profile=build_profile('albert','einstein', location='princeton', field='pyhsics') print(user_profile) #通用形參名**kwargs用于收集任意數(shù)量的關(guān)鍵字實(shí)參
7.5將函數(shù)存儲(chǔ)在模塊中
導(dǎo)入整個(gè)模塊
import文件要放在文件開頭
#下面這個(gè)模塊為pizza.py def make_pizza(size,*toppings): """概述要制作的比薩""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"-{topping}") #在pizza.py所在的目錄中創(chuàng)建一個(gè)名為making_pizzas.py的文件,并導(dǎo)入剛剛創(chuàng)建的模塊 import pizza #此行代碼會(huì)將pizza.py文件中的所有函數(shù)都復(fù)制到程序中 pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
導(dǎo)入模塊中的特定函數(shù)
from pizza import make_pizza,make_pizza2,make_pizza3 #使用逗號分隔開各個(gè)函數(shù),就可以導(dǎo)入任意數(shù)量的函數(shù) pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
使用as給函數(shù)指定別名
此方法可以給函數(shù)指定別名
from pizza import make_pizza as mp mp(16,'pepperoni') mp(12,'mushrooms','green peppers','extra cheese')
使用as給模塊指定別名
import pizza as p p.make_pizza(16,'pepperoni') p.make_pizza(12,'mushrooms','green peppers','extra cheese')
導(dǎo)入模塊中的所有函數(shù)
#使用星號*運(yùn)算符可以讓python導(dǎo)入模塊中的所有函數(shù) from pizza import* make_pizza(16,'pepperoni') make_pizza(12,'mushrooms','green peppers','extra cheese')
第8節(jié).類
8.1創(chuàng)建和使用類
使用類幾乎可以模擬任何東西
創(chuàng)建一個(gè)類
from _typeshed import Self class Dog: """一次模擬小狗的簡單嘗試""" def __init__(self,name,age): """初始化屬性name和age""" self.name=name #self.name=name獲取與形參name相關(guān)聯(lián)的值 self.age=age ### 以self為前綴的變量可以供類中所有方法使用 def sit(self): """模擬小狗收到命令時(shí)蹲下""" print(f"{self.name} is now sitting.") def roll_over(self): """模擬小狗收到命令時(shí)打滾""" print(f"{self.name} rolled over!")
根據(jù)類創(chuàng)建實(shí)例
class Dog: """一次模擬小狗的簡單嘗試""" def __init__(self,name,age): #形參self自動(dòng)向類中的方法傳遞指定的屬性 """初始化屬性name和age""" self.name=name self.age=age def sit(self): """模擬小狗收到命令時(shí)蹲下""" print(f"{self.name} is now sitting.") def roll_over(self): """模擬小狗收到命令時(shí)打滾""" print(f"{self.name} rolled over!") my_dog=Dog('Willie',6) #指定實(shí)例的屬性 print(f"My dog's name is {my_dog.name}.") #my_dog.name代碼用來訪問實(shí)例的屬性 print(f"My dog's name is {my_dog.age} years old.") my_dog=Dog('Willie',6) my_dog.sit() #調(diào)用實(shí)例的方法 my_dog.roll_over()
8.2使用類和實(shí)例
car類
class Car: """一次模擬汽車的簡單嘗試""" def __init__(self,make,model,year): """初始化描述汽車的屬性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整潔的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name())
給屬性指定默認(rèn)值
classclass Car: """一次模擬汽車的簡單嘗試""" def __init__(self,make,model,year): """初始化描述汽車的屬性。""" self.make=make self.model=model self.year=year self.odometer_reading=0 #創(chuàng)建一個(gè)名為odometer_reading的屬性,并將其初始值設(shè)為0,該值不會(huì)被傳遞給類的參數(shù)改變 def get_descriptive_name(self): """返回整潔的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一條指出汽車?yán)锍痰南?"" print(f"This car has {self.odometer_reading} miles on it.") my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name) my_new_car.read_odometer()
直接修改屬性的值
my_new_car.odometer_reading=23 my_new_car.read_odometer() ##通過方法修改屬性的值 class Car: """一次模擬汽車的簡單嘗試""" def __init__(self,make,model,year): """初始化描述汽車的屬性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整潔的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一條指出汽車?yán)锍痰南?"" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """將里程碑讀數(shù)設(shè)置為指定的值""" Self.odometer_reading=mileage my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) #在括號內(nèi)傳遞參數(shù) my_new_car.read_odometer()
8.3繼承
子類的方法__init__
一個(gè)類繼承 另一個(gè)類時(shí),它將自動(dòng)獲得另一個(gè)類的所有屬性和方法
class Car(): """一次模擬汽車的簡單嘗試""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0
繼承時(shí),父類必須包含在當(dāng)前文件中,且位于子類前面
def get_descriptive_name(self): long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading +=miles class ElectricCar(Car): """電動(dòng)汽車的獨(dú)特之處""" def __init__(self, make, model, year): """初始化父類的屬性""" super().__init__(make, model, year) my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name())
super() 是一個(gè)特殊函數(shù),幫助Python將父類和子類關(guān)聯(lián)起來。
在Python 2.7中,繼承語法稍有不同,函數(shù)super() 需要兩個(gè)實(shí)參:子類名和對象self
給子類定義屬性和方法
class Car: """一次模擬汽車的簡單嘗試""" def __init__(self,make,model,year): """初始化描述汽車的屬性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整潔的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一條指出汽車?yán)锍痰南?"" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """將里程碑讀數(shù)設(shè)置為指定的值""" Self.odometer_reading=mileage class ElectricCar(Car): """電動(dòng)汽車的獨(dú)特之處""" def __init__(self, make, model, year): """ 初始化父類的各項(xiàng)屬性 再初始化電動(dòng)汽車特有的屬性 """ super().__init__(make, model, year) self.battery_size=75 def describe_battery(self): """打印一條描述電瓶容量的消息""" print(f"This car has a {self.battery_size} -kwh battery.") my_tesla=ElectricCar('tesla','model s',2019) print(my_tesla.get_descriptive_name()) #調(diào)用父類的方法 my_tesla.describe_battery()
重寫父類的方法:
在子類中定義一個(gè)和父類中的某一方法同名的方法即可重寫父類中相應(yīng)的方法
將實(shí)例用作屬性
class Battery: """一次模擬電動(dòng)汽車電瓶的嘗試""" def __init__(self,battery_size=75): """初始化電瓶的屬性""" self.battery_size=battery_size def describe_battery(self): """打印一條描述電瓶容量的消息""" print(f"This car has a {self.battery_size} -kwh battery.")
導(dǎo)入類
使用from car import Car 可以從一個(gè)模塊中導(dǎo)入多個(gè)類,使用逗號隔開
最后給大家一個(gè)語法速查地圖(來自蟒蛇書)
點(diǎn)擊查看
附件: 編輯器安裝說明.pdf 389.53KB 下載次數(shù):2次
附件: Python背記手冊.pdf 0B 下載次數(shù):3次
附件: 蟒蛇PPTpython學(xué)習(xí)1-11章.zip 7.47MB 下載次數(shù):3次
附件: Python編程:從入門到實(shí)踐.pdf 4.98MB 下載次數(shù):2次
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。