閱讀目錄
一.if語句
1.1 功能
1.2 語法
1.2.1:單分支,單重條件判斷
1.2.2:單分支,多重條件判斷
1.2.3:if+else
1.2.4:多分支if+elif+else
1.2.5:if語句小結
1.3 案例
1.4 三元表達式
二.while語句
2.1 功能
2.2 語法
2.2.1:基本語法
2.2.2:計數循環
2.2.3:無限循環
2.2.4:while與break,continue,else連用
2.2.5:while語句小結
2.3 案例
三.for語句
3.1 功能
3.2 語法
3.2.1:基本語法
3.2.2:遍歷序列類型
3.2.3:遍歷可迭代對象或迭代器
3.2.4:for基於range()實現計數循環
3.2.5:for與break,continue,else
3.2.6:for語句小結
3.3 案例
四.練習
一.if語句
1.1 功能
計算機又被稱作電腦,意指計算機可以像人腦一樣,根據周圍環境條件(即expession)的變化做出不同的反應(即執行代碼)
if語句就是來控制計算機實現這一功能
1.2 語法
1.2.1:單分支,單重條件判斷
if expression:
expr_true_suite
註釋:expession爲真執行代碼expr_true_suite
1.2.2:單分支,多重條件判斷
if not active or over_time >= 10:
print('Warning:service is dead')
warn_tag+=1
1.2.3:if+else
if expression:
expr_true_suite
else:
expr_false_suite
1.2.4:多分支if+elif+else
if expession1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expession3:
expr3_true_suite
else:
none_of_the_above_suite
1.2.5:if語句小結
if 後表達式返回值爲True則執行其子代碼塊,然後此if語句到此終結,否則進入下一分支判斷,直到滿足其中一個分支,執行後終結if
expression可以引入運算符:not,and,or,is,is not
多重expression爲加強可讀性最好用括號包含
if與else縮進級別一致表示是一對
elif與else都是可選的
一個if判斷最多隻有一個else但是可以有多個elif
else代表if判斷的終結
expession可以是返回值爲布爾值的表達式(例x>1,x is not None)的形式,也可是單個標準對象(例 x=1;if x:print('ok'))
所有標準對象均可用於布爾測試,同類型的對象之間可以比較大小。每個對象天生具有布 爾 True 或 False 值。空對象、值爲零的任何數字或者 Null 對象 None 的布爾值都是 False。
下列對象的布爾值是 False
1.3 案例
#!/usr/bin/env python
#_*_coding:utf-8_*_
'''
提示輸入用戶名和密碼
驗證用戶名和密碼
如果錯誤,則輸出用戶名或密碼錯誤
如果成功,則輸出 歡迎,XXX!
'''
import getpass
name=input('用戶名: ')
passwd=getpass.getpass('密碼: ')
if name == 'tom' and passwd == '123':
print('welcome')
else:
print('get out')
1.4 三元表達式
語法:
expr_true_suite if expession else expr_false_suite
案例一:
>>> active=1
>>> print('service is active') if active else print('service is inactive')
service is active
案例二:
>>> x=1
>>> y=2
>>> smaller=x if x < y else y
>>> smaller
1
二.while語句
2.1 功能
while循環的本質就是讓計算機在滿足某一條件的前提下去重複做同一件事情(即while循環爲條件循環,包含:1.條件計數循環,2條件無限循環)
這一條件指:條件表達式
同一件事指:while循環體包含的代碼塊
重複的事情例如:從1加到10000,求1-10000內所有奇數,服務等待連接
2.2 語法
2.2.1:基本語法
while expression:
suite_to_repeat
註解:重複執行suite_to_repeat,直到expression不再爲真
2.2.2:計數循環
count=0
while (count < 9):
print('the loop is %s' %count)
count+=1
2.2.3:無限循環
count=0
while True:
print('the loop is %s' %count)
count+=1
tag=True
count=0
while tag:
if count == 9:
tag=False
print('the loop is %s' %count)
count+=1
2.2.4:while與break,continue,else連用
count=0
while (count < 9):
count+=1
if count == 3:
print('跳出本層循環,即徹底終結這一個/層while循環')
break
print('the loop is %s' %count)
count=0
while (count < 9):
count+=1
if count == 3:
print('跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環')
continue
print('the loop is %s' %count)
count=0
while (count < 9):
count+=1
if count == 3:
print('跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環')
continue
print('the loop is %s' %count)
else:
print('循環不被break打斷,即正常結束,就會執行else後代碼塊')
count=0
while (count < 9):
count+=1
if count == 3:
print('跳出本次循環,即這一次循環continue之後的代碼不再執行,進入下一次循環')
break
print('the loop is %s' %count)
else:
print('循環被break打斷,即非正常結束,就不會執行else後代碼塊')
2.2.5:while語句小結
條件爲真就重複執行代碼,直到條件不再爲真,而if是條件爲真,只執行一次代碼就結束了
while有計數循環和無限循環兩種,無限循環可以用於某一服務的主程序一直處於等待被連接的狀態
break代表跳出本層循環,continue代表跳出本次循環
while循環在沒有被break打斷的情況下結束,會執行else後代碼
2.3 案例
while True:
handle, indata = wait_for_client_connect()
outdata = process_request(indata)
ack_result_to_client(handle, outdata)
import getpass
account_dict={'alex':'123','eric':'456','rain':'789'}
count = 0
while count < 3:
name=input('用戶名: ').strip()
passwd=getpass.getpass('密碼: ')
if name in account_dict:
real_pass=account_dict.get(name)
if passwd == real_pass:
print('登陸成功')
break
else:
print('密碼輸入錯誤')
count+=1
continue
else:
print('用戶不存在')
count+=1
continue
else:
print('嘗試次數達到3次,請稍後重試')
三.for語句
3.1 功能
for 循環提供了python中最強大的循環結構(for循環是一種迭代循環機制,而while循環是條件循環,迭代即重複相同的邏輯操作,每次操作都是基於上一次的結果,而進行的)
3.2 語法
3.2.1:基本語法
for iter_var in iterable:
suite_to_repeat
註解:每次循環, iter_var 迭代變量被設置爲可迭代對象(序列, 迭代器, 或者是其他支持迭代的對 象)的當前元素, 提供給 suite_to_repeat 語句塊使用.
3.2.2:遍歷序列類型
name_list=['alex','eric','rain','xxx']
#通過序列項迭代
for i in name_list:
print(i)
#通過序列索引迭代
for i in range(len(name_list)):
print('index is %s,name is %s' %(i,name_list[i]))
#基於enumerate的項和索引
for i,name in enumerate(name_list,2):
print('index is %s,name is %s' %(i,name))
3.2.3:遍歷可迭代對象或迭代器
迭代對象:就是一個具有next()方法的對象,obj.next()每執行一次,返回一行內容所有內容迭代完後,
迭代器引發一 個 StopIteration 異常告訴程序循環結束. for 語句在內部調用 next() 並捕獲異常.
for循環遍歷迭代器或可迭代對象與遍歷序列的方法並無二致,只是在內部做了調用迭代器next(),並捕獲異常,終止循環的操作
很多時候你根本無法區分for循環的是序列對象還是迭代器
>>> f=open('a.txt','r')
for i in f:
print(i.strip())
hello
everyone
sb
3.2.4:for基於range()實現計數循環
range()語法:
range(start,end,step=1):顧頭不顧尾
range(10):默認step=1,start=0,生成可迭代對象,包含[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10):指定start=1,end=10,默認step=1,生成可迭代對象,包含[1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10,2):指定start=1,end=10,step=2,生成可迭代對象,包含[1, 3, 5, 7, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
注:for基於range()實現計數循環,range()生成可迭代對象,說明for循環本質還是一種迭代循環
3.2.5:for與break,continue,else
同while
3.2.6:for語句小結
for循環爲迭代循環
可遍歷序列成員(字符串,列表,元組)
可遍歷任何可迭代對象(字典,文件等)
可以用在列表解析和生成器表達式中
break,continue,else在for中用法與while中一致
3.3 案例
albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')
years = (1976, 1987, 1990, 2003)
#sorted:排序
for album in sorted(albums):
print(album)
#reversed:翻轉
for album in reversed(albums):
print(album)
#enumerate:
for i in enumerate(albums):
print(i)
#zip:組合
for i in zip(albums,years):
print(i)
四.練習
一、元素分類
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即: {'k1': 大於66的所有值, 'k2': 小於66的所有值}
二、查找
查找列表中元素,移除每個元素的空格,並查找以 a或A開頭 並且以 c 結尾的所有元素。
三、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
商品 li = ["手機", "電腦", '鼠標墊', '遊艇']
四、購物車
功能要求:
要求用戶輸入總資產,例如:2000
顯示商品列表,讓用戶根據序號選擇商品,加入購物車
購買,如果商品總額大於總資產,提示賬戶餘額不足,否則,購買成功。
附加:可充值、某商品移除購物車
goods = [
{"name": "電腦", "price": 1999},
{"name": "鼠標", "price": 10},
{"name": "遊艇", "price": 20},
{"name": "美女", "price": 998},
]
五、用戶交互,顯示省市縣三級聯動的選擇
dic = {
"河北": {
"石家莊": ["鹿泉", "藁城", "元氏"],
"邯鄲": ["永年", "涉縣", "磁縣"],
}
"河南": {
...
}
"山西": {
...
}
}