- 流程圖
-
三種程序設(shè)計(jì)基本結(jié)構(gòu)
- 順序結(jié)構(gòu)
- 選擇結(jié)構(gòu)
- 循環(huán)結(jié)構(gòu)
簡單分之
if語句格式
? 語句格式如下
if <condition>:
<body>
? 其中<condition>是條件表達(dá)式群凶,<body>是一個或多個語個或多個語句序列照藻。
? 先判斷<condition>條件:
? true竿开,則執(zhí)行<body>,再轉(zhuǎn)向下一條語句;
? false际乘,則直接跳過<body>诺核,轉(zhuǎn)向下一條語句;
簡單條件構(gòu)造
? 簡單條件基本形式
<expr> <relop> <expr>
? <relop>是關(guān)系操作符<, <=, ==, >=, >, !=
? 使用“=”表示賦值語句若专,使用“==”表示等于
? 除數(shù)字外许蓖,字符或字符串也可以按照字典順序用于條
比較
? <condition>是布爾表達(dá)式,為bool類型调衰,布爾值
真和假以字符True和False表示
二分之決策
? 二分支語法結(jié)構(gòu)如下:
if <condition>:
<statements>
else:
<statements>
? Python解釋器首先評估<condition>
? 如果<condition>是真的膊爪,if下面的語句被執(zhí)行
? 如果<condition>是假的,else下面的語句被執(zhí)行嚎莉。
多分之決策
? 把一個復(fù)合語句放到另一個語句的結(jié)構(gòu)之中稱
為嵌套米酬。下面是使用嵌套實(shí)現(xiàn)了三分支決策的
? 多分支決策是解決復(fù)雜問題的重要手段之一
? 一個三分支決策可以由兩個二分支結(jié)構(gòu)嵌套實(shí)現(xiàn)
? 使用if-else描述多分支決策時,實(shí)現(xiàn)更多分支需要更多嵌套趋箩,影響程序的易讀性
? Python使用if-elif-else描述多分支決策赃额,簡化分支結(jié)構(gòu)的嵌套問題
? 使用if-elif-else描述多分支決策:
if <conditionl>:
<casel1 statements>
elif <condition2>:
<case2 statements>
elif <condition3>:
<case3 statements>
......
else:
<sefault statements>
? Python輪流評估每個條件,來尋找條件為True的分支叫确,并
執(zhí)行該分支下的語句跳芳;如果沒有任何條件成立,else下面的
語句被進(jìn)行竹勉,else子句是可選的飞盆。
異常處理機(jī)制
異常處理機(jī)制的引入
? 如果處理錯誤或特殊情況的分支語句過多,那么處理正常
情況的主程序就會變得不清晰易讀饶米、
? 以前面講述的二次方程求解為例
discRt = otherSqrt(b*b-4*a*c)
if discRt < 0:
print("No real roots.")
else:
...
? 引入異常處理機(jī)制來解決程序運(yùn)行時的錯誤桨啃,而不是顯式
檢查算法的每一步是否成功。
異常處理語句
? Python使用try…except…來進(jìn)行異常處理檬输,基本
格式如下:
try:
<body>
except <ErrorType1>:
<handler1>
except <ErrorType2>:
<handler2>
except:
<handler0>
?當(dāng)Python解釋器遇到一個try語句照瘾,它會嘗試執(zhí)行
try語句體<body>內(nèi)的語句
?如果沒有錯誤,控制轉(zhuǎn)到try-except后面的語句
?如果發(fā)生錯誤丧慈,Python解釋器會尋找一個符合該錯誤
的異常語句析命,然后執(zhí)行處理代碼
TryException.py
def main():
try:
number1,number2 = eval(input("Enter teo numbers,separated by a comma")
result = number1 / number2
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("something wrong in the input")
else:
print("No exceptions,the result is ",result)
finally:
print("executing the final clause")
main()
? Try…except可以捕捉任何類型的錯誤
? 對于二次方程,還會有其他可能的錯誤逃默,如:輸入非數(shù)
值類型 (NameError)鹃愤,輸入無效的表達(dá)式(SyntaxError)
等。此時可以用一個try語句配多個except來實(shí)現(xiàn)完域。
基本循環(huán)結(jié)構(gòu)
for 循環(huán)
? Python可以使用for語句循環(huán)遍歷整個序列的值
for <var> in <sequence>:
<body>
? 在for循環(huán)中软吐,循環(huán)變量var遍歷了隊(duì)列中的每一個值,循
環(huán)的語句體為每個值執(zhí)行一次吟税。
def main():
words = ["sun","sunflower","want"]
for i in words:
print(i,":",len(i))
main()
? 注意凹耙,for循環(huán)在執(zhí)行過程中姿现,直接在序列上進(jìn)行
遍歷,而非在內(nèi)存中生成一個新的序列拷貝進(jìn)行
def main():
words = ["sun","sunflower","want"]
for i in words[:]:
if len(i) > 5:
words.insert(0,i)
print(i,":",len(i))
print(words)
main()
for循環(huán)-求平均數(shù)
? 平均數(shù)計(jì)算程序的IPO如下:
輸入:待輸入數(shù)字個數(shù)肖抱,數(shù)字
處理:平均數(shù)算法
輸出:平均數(shù)
? 通用設(shè)計(jì)方案:
輸入數(shù)字的個數(shù)n
將sum初始化為0
循環(huán)n次:
輸入數(shù)字x
將x加入sum中
將sum/n作為平均數(shù)輸出出來
for循環(huán)-代碼
def main():
n = eval(input("How many numbers?:"))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number:"))
sum = sum + x
print("\nThe average is : ",sum/n)
main()
for循環(huán)-執(zhí)行
? 以下是程序的執(zhí)行結(jié)果
How many numbers?:3
Enter a number:2
Enter a number:4
Enter a number:3
The average is : 3.0
for循環(huán)-缺點(diǎn)
? 程序開始時必須提供輸入數(shù)字總數(shù)
? 大規(guī)模數(shù)字求平均值需要用戶先數(shù)清楚個數(shù)
? for循環(huán)是需要提供固定循環(huán)次數(shù)的循環(huán)方式
? Python提供了另一種循環(huán)模式即無限循環(huán)备典,不需要提前
知道循環(huán)次數(shù),即我們提到的當(dāng)型循環(huán)也叫條件循環(huán)
無限循環(huán)
? 語法:while語句
while <condition>:
<body>
? while語句中<condition>是布爾表達(dá)式
? <body>循環(huán)體是一條或多條語句
? 當(dāng)條件<condition>為真時意述,循環(huán)體重復(fù)執(zhí)行
? 當(dāng)條件<condition>為假時提佣,循環(huán)終止
? 在while循環(huán)中,條件總是在循環(huán)頂部被判斷荤崇,即在循環(huán)
體執(zhí)行之前拌屏,這種結(jié)構(gòu)又被稱為前測循環(huán)
無限循環(huán)
? 下面是使用while循環(huán)完成從0到10的
求和打印平均值的例子:
? 如果循環(huán)體忘記累加i,條件判斷一直
為真天试,循環(huán)體將一直執(zhí)行槐壳,這就是所
謂的死循環(huán)程序
? 這時通常使用<Ctrl>-c來終止一個程
序
for/while 中的else, break用法
? Break 語句- 跳出最內(nèi)層for/while 循環(huán)
for/while 中的continue用法
? continue語句, 其作用為結(jié)束本次循環(huán)喜每。即跳出循環(huán)體中下
面尚未執(zhí)行的語句务唐,對于while循環(huán),繼續(xù)求解循環(huán)條件带兜。而
對于for循環(huán)程序流程接著遍歷循環(huán)列表
? continue語句和break語句的區(qū)別是:
? continue語句只結(jié)束本次循環(huán)枫笛,而不終止整個循環(huán)的執(zhí)行。而break語句則是結(jié)束整個循環(huán)過程刚照,不再判斷執(zhí)行循環(huán)的條件是否成立:
for/while 中的else用法
? Break 語句- 跳出最內(nèi)層for/while 循環(huán)
? <for… else: …> <while… else: …>語句與循環(huán)的搭配使
用刑巧,else:后的表達(dá)式在for循環(huán)列表遍歷完畢后或while 條
件語句不滿足的情況下執(zhí)行,例如:
#for/while 中的else 用法
for n in range(2,10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, "*", n//x)
break
else:
#loop fell through eithout finding a factor
print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
交互式循環(huán)
? 交互式循環(huán)是無限循環(huán)的一種
? 允許用戶通過交互的方式重復(fù)程序的特定部分
? 讓我們以交互循環(huán)的視覺重新審視求平均數(shù)程序
如下:
初始化sum為0
初始化count為0
初始化moredata為“yes”
當(dāng)moredata值為“yes”時
輸入數(shù)字x
將x 加入sum
count值加1
詢問用戶是否還有moredata需要處理
輸出sum/count
交互式循環(huán)代碼
# average2.py
def main():
sum = 0.0
count = 0
moredata = "yes"
while moredata[0] == 'y':
x = eval(input("Enter a nuber >>")
sum = sum + x
count = count + 1
moredata = input("Do you have more,numbers (yes or no)?")
print("\nThe average of the numbers is ",sum/count)
main()
# average3.py
def main():
sum = 0.0
count = 0
x = eval(input("Enter a number (negative to quit"))
while x >=0:
sum = sum + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >>"))
print("\n The average of the nubers is", sum/count)
main()
交互式循環(huán)執(zhí)行:
Enter a number >>30
Do you have more (yes or no)?y
Enter a number >>20
Do you have more (yes or no)?y
Enter a number >>30
Do you have more (yes or no)?y
Enter a number >>2
Do you have more (yes or no)?n
The avarage of the number is 20.5
哨兵循環(huán)
? 執(zhí)行循環(huán)直到遇到特定的值无畔,循環(huán)語句才終止執(zhí)行的循環(huán)結(jié)構(gòu)設(shè)計(jì)方法
? 哨兵循環(huán)是求平均數(shù)的更好方案啊楚,思路如下:
? 設(shè)定一個哨兵值作為循環(huán)終止的標(biāo)志
? 任何值都可以做哨兵,但要與實(shí)際數(shù)據(jù)有所區(qū)別偽代碼如下:
接收第一個數(shù)據(jù)
while這個數(shù)據(jù)不是哨兵
程序執(zhí)行相關(guān)語句
接收下一個數(shù)據(jù)項(xiàng)
在求考試分?jǐn)?shù)平均數(shù)的程序中浑彰,可以設(shè)定負(fù)數(shù)為哨兵
代碼如下:
# average3.py
def main():
sum = 0.0
count = 0
x eval(input("Enter a number (negative to quit) >>")
while x >=0:
sum = sum + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >>"))
print("\n The average of the numbers is ", sum/count)
main()
執(zhí)行結(jié)果:
Enter a number (negative to quit) >>1
Enter a number (negative to quit) >>2
Enter a number (negative to quit) >>3
Enter a number (negative to quit) >>4
Enter a number (negative to quit) >>5
Enter a number (negative to quit) >>6
Enter a number (negative to quit) >>7
Enter a number (negative to quit) >>-1
The average of the numbers is 4.0
? 沒有那么yes/no的干擾恭理,執(zhí)行結(jié)果更加清晰
? 但不能包含負(fù)數(shù)的平均數(shù)計(jì)算,為了更加通用化需要引入字符串
哨兵循環(huán)版本2
? 利用非數(shù)字字符串表示輸入結(jié)束
? 所有其他字符串將被轉(zhuǎn)換成數(shù)字作為數(shù)據(jù)處理
? 空字符串以 “ ”(引號中間沒有空格)代表郭变,可以真作為哨兵颜价,用戶輸入回車Python 就返回空字符串
? 偽代碼如下:
初始化sum為0
廚師還count為0
接受輸入的字符串?dāng)?shù)據(jù),xStr
while xStr非空
將xStr轉(zhuǎn)換為數(shù)字x
將x加入sum
count值加1
接受下個字符串?dāng)?shù)據(jù)诉濒,xStr
輸出sum/count
def main():
sum = 0.0
count = 0
xStr = input('Enter a number (<Ente> to quit>>')
while xStr !="":
x = eval(xStr)
sum = sum + x
xStr = input("Enter a number (<Enter> to quit)>>")
print("\n The average of the numbers is", sum / count)
執(zhí)行如下:
Enter a number (<Enter> to quit) >> 2
Enter a number (<Enter> to quit) >>4
Enter a number (<Enter> to quit) >>6
Enter a number (<Enter> to quit) >>78
Enter a number (<Enter> to quit) >>-45
Enter a number (<Enter> to quit) >>2
Enter a number (<Enter> to quit) >>0
Enter a number (<Enter> to quit) >>
The average of the number is 6.714285714285714
文件循環(huán)
? 面向文件的方法是數(shù)據(jù)處理的典型應(yīng)用
? 之前求平均數(shù)的數(shù)字都是用戶輸入的周伦,如果幾百個數(shù)求平均,輸入困難期容易出錯
? 可以事先將數(shù)據(jù)錄入到文件中未荒,然否將這個文件作為程序輸入专挪,避免人工輸入的麻煩, 便于編輯修改
文件循環(huán)代碼
# average5.py
def main():
fileName = input("What file are the numbers in")
infile = open(fileName, 'r')
sum = 0
count = 0
for line in infile:
sum += eval(line)
count +=1
print("\nThe average of the number is", sum/count)
main()
遍歷文件
? 在這段代碼中,循環(huán)變量line遍歷文件的每一行狈蚤,將每行都轉(zhuǎn)成數(shù)字加到sum中困肩。
? 通過Python的readerline()來讀取,reafline()將文件的每一行讀取到字符串中脆侮。
? 在文件尾部,resdderline()返回的一個空字符串可以作為哨兵值勇劣。
? Python中采用readerline()方法的end_of_file循環(huán)模式:
line = infile.readerline()
while line != "":
#處理每一行
line = infile.readerline()
文件循環(huán)代碼while
? 將end-of-file 哨兵循環(huán)應(yīng)用到平均數(shù)問題的代碼如下:
def main():
fileName = input("What file are the numbers in? ")
infile = open(fileName,"r")
sum = 0
count = 0
line = infile.readline()
while line !="":
sum = sum + eval(line)
count = count+1
line = infile.readerline()
print("\nThe average of number is", sum / count)
main()
嵌套循環(huán)
? 決策和循環(huán)互相嵌套可以實(shí)現(xiàn)復(fù)雜的算法
? 之前示例中文件每行值存一個數(shù)字靖避,這一次數(shù)字以逗號分割出現(xiàn)在文件的同一行上
? 下面是處理一行的代碼片段:
for xStr in file.split(","):
sum = sum + eval(xStr)
count = count+1
嵌套循環(huán)代碼
# average7.py
def main():
fileName = input("What file are the numbers in?")
infile = open(fileName, "r")
sum = 0.0
count = 0
line = infile.readerline()
while line !="":
#外循環(huán):while語句對沒行循環(huán)一次 #為line中的值更新其count和sum
for xStr in line.split(","):
#內(nèi)循環(huán):for語句對一行中的每個數(shù)字進(jìn)行循環(huán)
sum +=eval(xStr)
count +=1
line = infile.readerline()
print("\nThe average of the numbers is ", sum/count)
main()
死循環(huán)
死循環(huán)的使用
? 四循環(huán)并非一無是處,c語言中死循環(huán)while true或while 1 是單片機(jī)編程的普通用法比默,死循環(huán)一直運(yùn)行等待中斷程序發(fā)生幻捏,然后去處理中斷程序
? 在Python中我們也可以利用死循環(huán)完成特定功能
while True:
try:
x = int(input("Please enter a number:"))
break
except ValueError:
print("Oops, that was no valid number.Try again...")
代碼執(zhí)行如下:
Plece enter a number :k
Oops, that was no valid number. Try again...
Plece enter a number :k
Oops, that was no valid number. Try again...
Plece enter a number :9
后側(cè)循環(huán)
? 假設(shè)程序需要用戶輸入一個非負(fù)數(shù)
? 如果輸入錯誤,重新提示用戶輸入直到得到一個有效值
? 為代碼如下:
? 重復(fù)執(zhí)行以下語句
? 接受外部輸入數(shù)據(jù)
? 直到外部輸入為負(fù)值為止
? 循環(huán)不斷接收輸入命咐,直到接受到合法的值為止
? 條件判斷在循環(huán)體后面篡九,稱之為后測循環(huán)
? 后測循環(huán)至少執(zhí)行一次循環(huán)體
后側(cè)循環(huán)實(shí)現(xiàn)
? Python沒有后測循環(huán)語句,但可以通過while循環(huán)間接實(shí)現(xiàn)
? 思想是設(shè)計(jì)一個循環(huán)條件醋奠,直接進(jìn)入循環(huán)體榛臼,循環(huán)至少執(zhí)行一次,相當(dāng)于后測循環(huán)
nubmber = -1
while number < 0:
number = eval(input("Enter a positive number: "))
代碼執(zhí)行如下:
Enter a positive number: -1
Enter a positive number: -2
Enter a positive number: 3
? break語句也可以用來實(shí)現(xiàn)后側(cè)循環(huán)
while True:
number = eval(input("Enter a positive number:" ))
if x >= 0:
break
#如果數(shù)字有效則跳出循環(huán)
?while語句體永遠(yuǎn)執(zhí)行窜司,if條件決定循環(huán)退出
? 另外:if語句體只包含一個語句時沛善。break可以跟if在同一行
代碼執(zhí)行如下:
Enter a positive number:-1
Enter a positive number:0
后側(cè)循環(huán)代碼1
在前面的while版本的后側(cè)循環(huán)代碼中添加一個if語句,使得在有效輸入時不顯示警告
修改代碼如下:
number = -1
while number < 0:
number = eval(input("Enter a poditive number: "))
if number < 0:
print("The number you entered was not positive")
代碼執(zhí)行如下:
Enter a positive number:-1
The number you entered was not positive
Enter a positive number:-2
The number you entered was not positive
Enter a positive number:0
后側(cè)循環(huán)代碼2
? 限定合法性檢驗(yàn)只判斷一次塞祈,需為if添加匹配的else語句來實(shí)現(xiàn)
? 修改的代碼如下:
while True:
number = eval(input("Enter a positive number: "))
if x >= 0:
break #如果數(shù)字有效則跳出循環(huán)
else:
print("The number you entered was not positive")
代碼執(zhí)行如下:
Enter a positive number:-1
The number you entered was not positive
Enter a positive number:-5
The number you entered was not positive
Enter a positive number:9
半路循環(huán)
運(yùn)用break中途退出循環(huán)金刁, 循環(huán)出口在循環(huán)體中部,被稱為半路循環(huán)
while True:
number = eval(input("Enter a positive number:"))
if x >=0: break #跳出循環(huán)
print("The number you entered was not positive")
半路循環(huán)——哨兵
半路循環(huán)退出實(shí)現(xiàn)哨兵循環(huán)的一般模式
while True:
Get next data item
if the item is the sentinrl: break
process thw item
在程序中是否使用break語句议薪,跟個人編程風(fēng)格有關(guān)尤蛮。
應(yīng)避免在一個循環(huán)體內(nèi)使用過多的break語句。因?yàn)楫?dāng)循環(huán)有多個出口的時候斯议,程序邏輯就顯得不過清晰了产捞。
布爾表達(dá)式
? 條件語句和循環(huán)語句都使用布爾表達(dá)式作為條件
? 布爾值為真或假,以False和True表示
? 前面經(jīng)常使用布爾表達(dá)式比較兩個值捅位,如:while x>= 0
布爾操作符的引入
? 簡單條件在復(fù)雜決策情況下存在缺陷
? 例如轧葛,確定兩個點(diǎn)是否是在同一個位置,即是否有相同的x坐標(biāo)和y坐標(biāo)艇搀,下面是處理的代碼片段:
if p1.getX() == p2.getX():
if p1.getY() == p2.getY():
# 兩點(diǎn)相同
else:
# 兩點(diǎn)不同
else:
#兩點(diǎn)不同
過于復(fù)雜尿扯,Python提供了更簡單的布爾操作符來構(gòu)建表達(dá)式
布爾操作符
? 布爾操作符: and ,or 和 not
? 布爾操作符and和or用于組合兩個布爾表達(dá)式,并產(chǎn)生一個布爾結(jié)果
? <expr> and <expr>
? <expr> or <expr>
? not運(yùn)算符是一個一元運(yùn)算符焰雕,用來計(jì)算一個布爾表達(dá)式的反
? not <expr>
? 使用布爾運(yùn)算符衷笋,可以建立任意復(fù)雜的布爾表達(dá)式
例如:a or not b and c
? Python中布爾操作符的優(yōu)先級,從高分到低分依次是not,and最低是or.所以上面的表達(dá)式等于如下這個帶有括號的版本:(a or ((not b) and c))
? 使用and操作符改進(jìn)之前比較兩個點(diǎn)相同的例子
if p1.getX() == p2.getX() and p2.getY() == p1.getY():
#兩點(diǎn)相同
else:
#兩點(diǎn)不同
簡單矩屁,清晰
壁球比賽積分例子
? 假設(shè)scoreA和scoreB代表兩個選手分?jǐn)?shù)
? 規(guī)則: 只要一個選手達(dá)到了15分辟宗,本場比賽就結(jié)束爵赵。
? 即如下布爾表達(dá)式為真時比賽結(jié)束:
scoreA == 15 or scoreB == 15
? 可以構(gòu)造循環(huán)條件,對游戲結(jié)束條件取反:
while not(scoreA == 15 or scoreB == 15):
# 比賽繼續(xù)
? a和b 代表兩個壁球選手的分?jǐn)?shù)
? 規(guī)則1: 只要一個選手達(dá)到了15分泊脐,本場比賽就結(jié)束空幻,如果一方打了七分而另一方一分未得時,比賽也會結(jié)束
(a>=15 or b >= 15) and abs(a-b)>=2
? 規(guī)則2:需要一個團(tuán)隊(duì)贏得至少兩分才算贏容客,即其中一個隊(duì)已經(jīng)達(dá)到了15分秕铛,且分?jǐn)?shù)差異至少為2時比賽結(jié)束
(排球) (a >= 15 and a-b>=2) or (b>=15 and b-a >=2)
? 等價(jià)于 (a>=15 or b<=15) and abs(a-b)>=2
abs函數(shù)返回表達(dá)式的絕對值
布爾代數(shù)
? 布爾表達(dá)式遵循特定的代數(shù)定律,這些規(guī)律被稱為布爾邏輯或布爾代數(shù)
? 布爾代數(shù)規(guī)則
Algebra | Boolearn algebra |
---|---|
a*0 = 0 | a and false == false |
a*1 = a | a and true == a |
a+0 = a | a or false == a |
?當(dāng)0和1對應(yīng)false和true時
?and與乘法相似
?or與加法相似
條件輸入:
def main():
a ,b= eval(input("Pleace enter a and b number:"))
while True:
if (a >=15 or b>=15) and abs(a-b)>=2:
print("The game over" ,abs(a-b))
break
else:
print("Pleace enter two number again")
a ,b= eval(input("Pleace enter a and b number:"))
main()
代碼執(zhí)行如下:
Pleace enter a and b number:12,13
Pleace enter two number again
Pleace enter a and b number:12,45
The game over 33
? 任何值和true進(jìn)行 “or” 操作都是真
a or true == true
? and 和 偶然操作符都符合分配率:
a or (b and c) == (a or b) and (a or c)
a and (b or c) == (a and b) or (a and c)
? not 操作符具有負(fù)負(fù)抵消的特征:
not(not a) == a
?布爾代數(shù)符合德摩根定律缩挑,not放進(jìn)表達(dá)式后但两,and和運(yùn)算符之間發(fā)生都得變化:
not (a or b) == (not a) and (not b)
not(a and b) == (not a) or (not b)
? 布爾代數(shù)的應(yīng)用
while not (scoreA == 15 or scoreB == 15):
#比賽繼續(xù)
? 通過使用布爾代數(shù), 可以轉(zhuǎn)換上面這個表達(dá)式供置。應(yīng)用德摩根定律谨湘,其等同于下面這個表達(dá)式:
(not scoreA ==15) and (not scoreB ==15)
? 注意,當(dāng)使用not的分分配率時,or和and的轉(zhuǎn)變。
while scoreA != 15 and scpreB !=15:
# 比賽繼續(xù)
布爾表達(dá)式作為決策
? 在Python中蒲列,布爾表達(dá)式是很靈活的。
? 回顧交付式循環(huán)寓辱,只要用戶相應(yīng)一個“Y”,程序就繼續(xù)。
while response[0] == "y" or response[0] == "Y"
? 初學(xué)者注意不要將上述表達(dá)式寫成以下的形式
while response[0]== "y" or "Y":
? 其實(shí)這是一個無限循環(huán)赤拒。請思考為什么哲理的條件表達(dá)式值總為真秫筏?
? Python的條件運(yùn)算符(即==)總是在與一個bool類型的值進(jìn)行比較!
?布爾True和False來代表布爾值的真和假
? 對于數(shù)字(整型和浮點(diǎn)型)的零值被認(rèn)為是false
?任何非零值都是True
? bool 類型僅僅是一個特殊的整數(shù)挎挖,可以通過計(jì)算表達(dá)式 True + True的值來測試一下
? 對于系列類型來說这敬,一個空系列解釋為假,任何一個非空系列解釋為真
bool(0)
False
bool(1)
True
bool(32)
True
bool("helllo")
True
bool("")
False
bool([1,2,3])
True
bool([])
False
布爾表達(dá)式思考
? Python的布爾靈活也擴(kuò)展到了布爾運(yùn)算符蕉朵。下表總結(jié)了這些運(yùn)算符都得特征
operator | operational definition |
---|---|
x and y | If x is false, return x.Otherwise, return y |
x or y | If x is true, return x, Otherwise, return y |
not x | If x is false , return True,Otherwise, return False |
? Pytnon的布爾運(yùn)算符是短路運(yùn)算符崔涂。
? Python從左到右掃描表達(dá)式一旦知道結(jié)果,就立即返回True或False值
while response[0] == "y" or response[0]=="Y":
while response[0] == "y" or "Y"
思考上面兩條代表碼有何區(qū)別
? 第二個表達(dá)式“Y”, 它是一個非空的字符串始衅,所以Python會永遠(yuǎn)把它解釋為真
### 布爾表達(dá)式簡潔表示
? 如果用戶僅僅簡單敲下回車鍵冷蚂,可以使用方括號中的值作為默認(rèn)值
ans = input("What flavor do you want [vanilla]:")
if ans !="":
flavor = ans
else:
flavor = "vanilla"
? 可以簡化如下:
ans = input("What flavor do you want [vanilla]:")
if ans:
flavor = ans
else:
flavor = "vanilla"
? 更簡單的表達(dá)形式
ans = input("What flavor do you want [vanilla]:")
flavor= ans or "vanilla"
? or 操作符的定義保證它等價(jià)于if-else結(jié)構(gòu),
? 進(jìn)一步簡化:
flavor = input("What flavor do you want [vanilla]:") or "vanilla"