第六章 字典
- 在python中 ,字典是一系列鍵值對,每個鍵都與一個值關(guān)聯(lián),可以使用鍵來訪問與之相關(guān)聯(lián)的值;
- 與之關(guān)聯(lián)的值可是數(shù)字、列表甚至字典;
- 事實上,可將任何Python對象用作字典中的值;鍵和值之間用冒號分隔;
- 字典用放在花括號{}中的一系列鍵對表示。
- 訪問字典中的值
alien_0={'color':'green',"points":5}
print(alien_0['color'])#字典取值,用[]里面加對應(yīng)的鍵
#運行結(jié)果:
green
- 字典是一種動態(tài)結(jié)構(gòu),可隨時添加鍵值對,依次指定字典名、用方括號括起來的鍵和相關(guān)聯(lián)的值
alien_0={'color':'green',"points":5}
alien_0['x_pos']=0
alien_0['y_pos']=25
print(alien_0)
#運行結(jié)果:
{'color': 'green', 'points': 5, 'x_pos': 0, 'y_pos': 25}
- 空字典
aline_0={}
- 修改字典中的值,依次指定字典名、用方括號括起來的鍵以及與該鍵相關(guān)的新值
alien_0={'color':'green',"points":5}
alien_0['color']='red'
print(alien_0)
#運行結(jié)果:
{'color': 'red', 'points': 5}
- 刪除鍵值對,用del語句將相應(yīng)的鍵值對徹底刪除
alien_0={'color':'green',"points":5}
del alien_0['points']
print(alien_0)
#運行結(jié)果:
{'color': 'green'}
- 遍歷字典,可使用for循環(huán)來遍歷字典,先聲明兩個變量,用于存儲鍵值 對中的鍵和值,for語就只有的第二部分包含字典和方法items(),返回一個鍵值對列表,接下來,for循環(huán)依次將每個鍵值對存儲到指定的兩個變量中。
alien_0={'color':'green',"sex":'F'}
for k,v in alien_0.items():
print("\nKey:"+k)
print("\nValue:"+v)
#運行結(jié)果:
Key:color
Value:green
Key:sex
Value:F
- 遍歷所有鍵,方法keys()返回鍵列表。
alien_0={'color':'green',"sex":'F'}
for key in alien_0.keys():
print(key)
#運行結(jié)果:
color
sex
- 遍歷所有值,方法values()返回鍵列表,可使用set()刪除重復(fù)的值。
alien_0={'color':'green',"sex":'F'}
for value in alien_0.values():
print(value)
#運行結(jié)果:
green
F
- 嵌套
a. 字典列表
alien_0={'color':'green',"sex":'M'}
alien_1={'color':'red',"sex":'F'}
alien_2={'color':'yellow',"sex":'M'}
aliens=[alien_0,alien_1,alien_2]
print(aliens)
#運行結(jié)果:
[{'color': 'green', 'sex': 'M'}, {'color': 'red', 'sex': 'F'}, {'color': 'yellow', 'sex': 'M'}]
b. 在字典中存儲列表
favorite_languages={'jimmy':['delphi','javascript','python'],
'jenny':['python'],
'jack':['python'],
}
for name,languages in favorite_languages.items():
print('\n'+name.title() + "'s favorite languages are:")
for language in languages:
print('\t' + language.title())
#運行結(jié)果:
Jimmy's favorite languages are:
Delphi
Javascript
Python
Jenny's favorite languages are:
Python
Jack's favorite languages are:
Python
c. 在字典中存儲字典
runner={
'DK':{
'dept':'IT',
'level':'A'
},
'John':{
'dept':'PM',
'level':'A'
},
}
for name,info in runner.items():
print('\nname:' + name)
dept=info['dept']
level=info['level']
print('\tFrom dept:' + dept)
print('\trun level:' + level)
#運行結(jié)果:
name:DK
From dept:IT
run level:A
name:John
From dept:PM
run level:A
第七章 用戶輸入和while循環(huán)
一. 函數(shù)input()的工作原理
函數(shù)input()讓程序暫停運行,等待用戶輸入一些文本,獲取用戶輸入后,Python將其存儲在一個變量中,以便使用。
message = input('tell me something:')
print(message)
二. 取余運算符
%取余運算,返兩數(shù)個相除的余數(shù)。
print(4 % 3)
#運行結(jié)果:
1
三. while 循環(huán)
- for循環(huán)用于針對集合中的每個元素都執(zhí)行一個代碼塊,而while循環(huán)不斷地運行,直到指定的條件不滿足為止。
#例1
num=1
while num<3:
print(num)
num+=1
#運行結(jié)果:
1
2
#例2
prompt='\ntell me somethine, and I will repeat it back to you:'
promtp+='\nEnter "q" to end the program.'
msg=''
while msg != 'q':
msg=input(prompt)
print(msg)
- 使用break退出循環(huán)
#例1
num=1
while num<5:
if num % 2 == 0:
break
print(num)
num+=1
#運行結(jié)果:
1
- 循環(huán)使用continue
num=0
while num<5:
num+=1
if num % 2 == 0:
print(num)
continue
#運行結(jié)果:
2
4
- 使用while循環(huán)處理列表和字典
a. 列表之間移動元素
b. 刪除包含特定值的所有列表元素
c. 使用用戶輸入來填充字典
第八章 函數(shù)
一. 定義函數(shù)
- 使用關(guān)鍵字def來告訴Python定義一個函數(shù),指出函數(shù)名,在括號內(nèi)指出函數(shù)為完成其任務(wù)需要什么樣的信息,也可以不指定,即便為空,括號必不可少,最后以冒號結(jié)尾。
#例2
def greet_user():
print('Hello')
greet_user()
#運行結(jié)果:
Hello
#例2
def greet_user(name): #name:形參
print('Hello '+name.title())
greet_user('Kobe') #Kobe:實參
#運行結(jié)果:
Hello Kobe
- 傳遞實參
鑒于函數(shù)定義中可能包含多個形參,因此函數(shù)調(diào)用中也可能包含多個實參,向函數(shù)傳遞實參的方式:位置實參,要求實參的順序與形參的順序相同;使用關(guān)鍵字實參,其中每個實參都由變量名和值組成;還可使用列表和字典。
a. 位置實參,調(diào)用時,必須將函數(shù)中的每個實參都關(guān)聯(lián)到函數(shù)定義中的一個形參,因此最簡單的關(guān)聯(lián)方式是基于實參順序
def user_info(name,sex):
print("\nI'm " + name.title())
print("My sex is " + sex)
user_info('Kobe','Man')
#運行結(jié)果:
I'm Kobe
My sex is Man
b. 關(guān)鍵字實參,是傳遞給函數(shù)的名稱-值對,直接在實參中將名稱和值關(guān)聯(lián)起來,所以向函數(shù)傳遞實參時不會混淆,無需考慮函數(shù)調(diào)用實參的順序,還清楚地指出函數(shù)調(diào)用各個值的用途。使用關(guān)鍵字實參時,必須準(zhǔn)確地指定函數(shù)定義中的形參名
def user_info(name,sex):
print("\nI'm " + name.title())
print("My sex is " + sex)
user_info('Kobe','Man')
user_info(sex='Man',name='Kobe')
#運行結(jié)果:
I'm Kobe
My sex is:Man
I'm Kobe
My sex is Man
c. 默認(rèn)值,編寫函數(shù)時,可給每個形參指默認(rèn)值,如果調(diào)用中給形參提供了實參,將使用指定的實參值,否則,將使用默認(rèn)值。形參指定默認(rèn)值后,調(diào)用時可省略相應(yīng)的實參。
def user_info(name,sex='Femal'):
print("\nI'm " + name.title())
print("My sex is " + sex)
user_info('Jesse')
user_info(sex='Man',name='Kobe')
#運行結(jié)果:
I'm Jesse
My sex is:Femal
I'm Kobe
My sex is Man
- 返回值,在函數(shù)中使用return語句將值返回到調(diào)用函數(shù)的代碼行,返回值 讓你能夠?qū)⒊绦虻拇蟛糠址敝氐墓ぷ饕频胶瘮?shù)中去完成,從而簡化主程序。函數(shù)可以返回任何類型的值
a. 返回單個值
def get_full_name(first_name,middle_name,last_name):
full_name=first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
full_name=get_full_name('john','lee','hooker'):
print(full_name)
#運行結(jié)果:
John lee hooker
b. 返回字典
def build_user(first_name,middle_name,last_name):
user={'first':first_name,'middle':middle_name , 'last' : last_name}
return user
user=build_user('john','lee','hooker')
print(user)
#運行結(jié)果:
{'first': 'john', 'middle': 'lee', 'last': 'hooker'}
- 傳遞列表
傳遞原列表,函數(shù)可以修改和刪除列表;要想保持原來列表不變,調(diào)用時可傳遞列表副本(例2)
#例1
def greet_user(names):
for name in names:
print('Hello '+name.title())
greet_user(['Kobe','Curry'])
#運行結(jié)果:
Hello Kobe
Hello Curry
#例2
def greet_user(un_greet_users,greeted_users):
while un_greet_users:
name=un_greet_users.pop()
greeted_users.append(name)
un_greet_users=['Kobe','Curry']
greeted_users=[]
greet_user(un_greet_users,greeted_users)
print('First call greet_user Result:')
print(un_greet_users)
print(greeted_users)
un_greet_users=['Kobe','Curry']
greeted_users=[]
greet_user(un_greet_users[:],greeted_users)
print('Second call greet_user Result:')
print(un_greet_users)
print(greeted_users)
#運行結(jié)果:
First call greet_user Result:
[]
['Curry', 'Kobe']
Second call greet_user Result:
['Kobe', 'Curry']
['Curry', 'Kobe']
- 傳遞任意數(shù)量的實參
def make_pizza(*toppings):
print(toppings)
make_pizza('apple')
make_pizza('pear','rice','fish')
#運行結(jié)果:
('apple',)
('pear', 'rice', 'fish')
#例2
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppins:
print('-' + topping)
make_pizza('apple')
make_pizza('pear','rice','fish')
#運行結(jié)果:
Making a pizza with the following toppings:
-apple
Making a pizza with the following toppings:
-pear
-rice
-fish
形參*toppings中的*號讓Python創(chuàng)建一個名為toppings的空元組,并將收到的所有值都封裝到這個元組中,即使用只有一個也是如此
- 使用任意數(shù)量的關(guān)鍵字實參
def build_user(name,**user_info):
profile={}
profile['name']=name
for key,value in user_info.items():
profile[key]=value
return profile
user_info=build_user('Kobe',team='Lakers',age=40)
print(user_info)
#運行結(jié)果:
{'name': 'Kobe', 'team': 'Lakers', 'age': 40}
形參**user_info中的兩個星號讓Python創(chuàng)建一個名為user_info的空字典,并將收到的所有名稱-值對都封裝到這個字典中。
7.將函數(shù)存儲在模塊中
函數(shù)的優(yōu)點之一是,使用它們可將代碼塊與主程序分離,通過函數(shù)措定描述性名稱,可讓主程序容易理解;
還可以在將函數(shù)存儲在被稱為獨立模塊的獨立文件中,再將模塊導(dǎo)入到主程序中,import語句允許在當(dāng)前運行的程序文件中使用模塊中的代碼。
a. 導(dǎo)入整個模塊: import 模塊名,模塊名是擴展名為.py的文件
b. 導(dǎo)入特定函數(shù):from 模塊名 import 函數(shù)名
c. 使用as給函數(shù)指定別名:from 模塊名 import 函數(shù)名 as 別名
d. 使用as給模塊指定別名:import 模塊名 as 別名
e. 導(dǎo)入模塊中所有函數(shù):from 模塊名 import *,可以通過函數(shù)名稱直接調(diào)用函數(shù),無需使用句點表示法
- 函數(shù)編寫指南
給函數(shù)指定描述性名稱,且只在其中使用小寫字母和下劃線
每個函數(shù)都應(yīng)包含簡要闡述其功能的注釋,該注釋應(yīng)緊跟在函數(shù)定義后面,并采用文檔字符串格式